home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 21 / Cream of the Crop 21 (Terry Blount) (October 1996).iso / os2 / e33el2.zip / emacs / 19.33 / lisp / viper.el < prev    next >
Text File  |  1996-08-04  |  199KB  |  5,636 lines

  1. ;;; viper.el --- A full-featured Vi emulator for GNU Emacs 19 and XEmacs 19,
  2. ;;         a VI Plan for Emacs Rescue,
  3. ;;         and a venomous VI PERil.
  4. ;;         Viper Is also a Package for Emacs Rebels.
  5. ;;
  6. ;;  Keywords: emulations
  7. ;;  Author: Michael Kifer <kifer@cs.sunysb.edu>
  8.  
  9. ;; Copyright (C) 1994, 1995, 1996 Free Software Foundation, Inc.
  10.  
  11. (defconst viper-version "2.90 of June 19, 1996"
  12.   "The current version of Viper")
  13.  
  14. ;; This file is part of GNU Emacs.
  15.  
  16. ;; GNU Emacs is free software; you can redistribute it and/or modify
  17. ;; it under the terms of the GNU General Public License as published by
  18. ;; the Free Software Foundation; either version 2, or (at your option)
  19. ;; any later version.
  20.  
  21. ;; GNU Emacs is distributed in the hope that it will be useful,
  22. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  24. ;; GNU General Public License for more details.
  25.  
  26. ;; You should have received a copy of the GNU General Public License
  27. ;; along with GNU Emacs; see the file COPYING.  If not, write to the
  28. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  29. ;; Boston, MA 02111-1307, USA.
  30.  
  31. ;;; Commentary:
  32.  
  33. ;; Viper is a full-featured Vi emulator for Emacs 19.  It emulates and
  34. ;; improves upon the standard features of Vi and, at the same time, allows
  35. ;; full access to all Emacs facilities.  Viper supports multiple undo,
  36. ;; file name completion, command, file, and search history and it extends
  37. ;; Vi in many other ways. Viper is highly customizable through the various
  38. ;; hooks, user variables, and keymaps.  It is implemented as a collection
  39. ;; of minor modes and it is designed to provide full access to all Emacs
  40. ;; major and minor modes.
  41. ;;
  42. ;;; History
  43. ;;
  44. ;; Viper is a new name for a package formerly known as VIP-19,
  45. ;; which was a successor of VIP version 3.5 by Masahiko Sato
  46. ;; <ms@sail.stanford.edu> and VIP version 4.2 by Aamod Sane
  47. ;; <sane@cs.uiuc.edu>. Some ideas from vip 4.4.2 by Aamod Sane
  48. ;; were also shamelessly plagiarized.
  49. ;;
  50. ;; Viper maintains some degree of compatibility with these older
  51. ;; packages. See the documentation for customization.
  52. ;;
  53. ;; The main difference between Viper and these older packages are:
  54. ;;
  55. ;; 1. Viper emulates Vi at several levels, from almost complete conformity
  56. ;;    to a rather loose Vi-compliance.
  57. ;;
  58. ;; 2. Viper provides full access to all major and minor modes of Emacs
  59. ;;    without the need to type extra keys.
  60. ;;    The older versions of VIP (and other Vi emulators) do not work with
  61. ;;    some major and minor modes.
  62. ;;
  63. ;; 3. Viper supports vi-style undo.
  64. ;;
  65. ;; 4. Viper fully emulates (and improves upon) vi's replacement mode.
  66. ;;
  67. ;; 5. Viper has a better interface to ex, including command, variable, and
  68. ;;    file name completion.
  69. ;;
  70. ;; 6. Viper uses native Emacs history and completion features; it doesn't
  71. ;;    rely on other packages (such as gmhist.el and completer.el) to provide
  72. ;;    these features.
  73. ;;
  74. ;; 7. Viper supports Vi-style editing in the minibuffer, by allowing the
  75. ;;    user to switch from Insert state to Vi state to Replace state, etc.
  76. ;;
  77. ;; 8. Viper keeps history of recently inserted pieces of text and recently
  78. ;;    executed Vi-style destructive commands, such as `i', `d', etc.
  79. ;;    These pieces of text can be inserted in later insertion commands;
  80. ;;    the previous destructive commands can be re-executed.
  81. ;;
  82. ;; 9. Viper has Vi-style keyboard macros, which enhances the similar
  83. ;;    facility in the original Vi.
  84. ;;    First, one can execute any Emacs command while defining a
  85. ;;    macro, not just the Vi commands. Second, macros are defined in a
  86. ;;    WYSYWYG mode, using an interface to Emacs' WYSIWYG style of defining
  87. ;;    macros. Third, in Viper, one can define macros that are specific to
  88. ;;    a given buffer, a given major mode, or macros defined for all buffers.
  89. ;;    The same macro name can have several different definitions:
  90. ;;    one global, several definitions for various major modes, and
  91. ;;    definitions for specific buffers.
  92. ;;    Buffer-specific definitions override mode-specific
  93. ;;    definitions, which, in turn, override global definitions.
  94. ;;
  95. ;;
  96. ;;; Installation:
  97. ;;  -------------
  98. ;;
  99. ;;  (require 'viper)
  100. ;;
  101.  
  102. ;;; Acknowledgements:
  103. ;;  -----------------
  104. ;;  Bug reports and ideas contributed by many users have helped
  105. ;;  improve Viper and the various versions of VIP.
  106. ;;  See the on-line manual for a complete list of contributors. 
  107. ;;
  108. ;;
  109. ;;; Notes:
  110. ;;
  111. ;; 1. Major modes.
  112. ;; In most cases, Viper handles major modes correctly, i.e., they come up
  113. ;; in the right state (either  vi-state or emacs-state). For instance, text
  114. ;; files come up in vi-state, while, say, Dired appears in emacs-state by
  115. ;; default. 
  116. ;; However, some modes do not appear in the right mode in the beginning,
  117. ;; usually because they neglect to follow Emacs conventions (e.g., they don't
  118. ;; use kill-all-local-variables when they start). Some major modes
  119. ;; may fail to come up in emacs-state if they call hooks, such as
  120. ;; text-hook, for no good reason. 
  121. ;; 
  122. ;; As an immediate solution, you can hit C-z to bring about the right mode.
  123. ;; An interim solution is to add an appropriate hook to the mode like this:
  124. ;; 
  125. ;;     (add-hook 'your-favorite-mode 'viper-mode)
  126. ;; or    
  127. ;;     (add-hook 'your-favorite-mode 'vip-change-state-to-emacs)
  128. ;; 
  129. ;; whichever applies. The right thing to do, however, is to complain to the
  130. ;; author of the respective package. (Sometimes they also neglect to equip
  131. ;; their  modes with hooks, which is one more reason for complaining.)
  132. ;; 
  133. ;; 2. Keymap handling
  134. ;;    Because Emacs 19 has an elegant mechanism for turning minor mode keymaps
  135. ;;    on and off, implementation of Viper has been greatly simplified. Viper
  136. ;;    has several minor modes.
  137. ;;
  138. ;; Viper's  Vi state consists of seven minor modes:
  139. ;;
  140. ;;  vip-vi-intercept-minor-mode
  141. ;;  vip-vi-local-user-minor-mode
  142. ;;  vip-vi-global-user-minor-mode
  143. ;;  vip-vi-kbd-minor-mode
  144. ;;  vip-vi-state-modifier-minor-mode
  145. ;;  vip-vi-diehard-minor-mode
  146. ;;  vip-vi-basic-minor-mode
  147. ;;
  148. ;;  Bindings done to the keymap of the first mode overshadow those done to
  149. ;;  the second, which, in turn, overshadows those done to the third, etc.
  150. ;;
  151. ;;  The last vip-vi-basic-minor-mode contains most of the usual Vi bindings
  152. ;;  in its edit mode. This mode provides access to all Emacs facilities.
  153. ;;  Novice users, however, may want to set their vip-expert-level to 1
  154. ;;  in their .vip file. This will enable vip-vi-diehard-minor-mode. This
  155. ;;  minor mode's bindings make Viper simulate the usual Vi very closely.
  156. ;;  For instance,  C-c will not have its standard Emacs binding
  157. ;;  and so many of the goodies of Emacs are not available.
  158. ;;
  159. ;;  A skilled user should set vip-expert-level to at least 3. This will
  160. ;;  enable `C-c' and many Emacs facilities will become available.
  161. ;;  In this case, vip-vi-diehard-minor-mode is inactive.
  162. ;;
  163. ;;  Viper gurus should have at least
  164. ;;      (setq vip-expert-level 4)
  165. ;;  in their ~/.vip files. This will unsuppress all Emacs keys that are not
  166. ;;  essential for VI-style editing.
  167. ;;  Pick-and-choose users may want to put
  168. ;;      (setq vip-expert-level 5)
  169. ;;  in ~/.vip. Viper will then leave it up to the user to set the variables
  170. ;;  vip-want-*  See vip-set-expert-level for details.
  171. ;;
  172. ;;  The very first minor mode, vip-vi-intercept-minor-mode, is of no
  173. ;;  concern for the user. It is needed to bind Viper's vital keys, such as
  174. ;;  ESC and C-z.
  175. ;;
  176. ;;  The second mode,  vip-vi-local-user-minor-mode, usually has an
  177. ;;  empty keymap. However, the user can set bindings in this keymap, which
  178. ;;  will overshadow the corresponding bindings in the other two minor
  179. ;;  modes. This is useful, for example, for setting up ZZ in gnus,
  180. ;;  rmail, mh-e, etc., to send  message instead of saving it in a file.
  181. ;;  Likewise, in Dired mode, you may want to bind ZN and ZP to commands
  182. ;;  that would visit the next or the previous file in the Dired buffer.
  183. ;;  Setting local keys is tricky, so don't do it directly. Instead, use
  184. ;;  vip-add-local-keys function (see its doc).
  185. ;;
  186. ;;  The third minor mode, vip-vi-global-user-minor-mode, is also intended
  187. ;;  for the users but, unlike vip-vi-local-user-minor-mode, its key
  188. ;;  bindings are seen in all Viper buffers. This mode keys can be done
  189. ;;  with define-key command.
  190. ;;
  191. ;;  The fourth minor mode, vip-vi-kbd-minor-mode, is used by keyboard
  192. ;;  macros. Users are NOT supposed to modify this keymap directly.
  193. ;;
  194. ;;  The fifth mode, vip-vi-state-modifier-minor-mode, can be used to set
  195. ;;  key bindings that are visible in some major modes but not in others.
  196. ;;
  197. ;;  Users are allowed to modify keymaps that belong to
  198. ;;  vip-vi-local-user-minor-mode, vip-vi-global-user-minor-mode,
  199. ;;  and vip-vi-state-modifier-minor-mode only.
  200. ;;
  201. ;;  Viper's Insert state also has seven minor modes:
  202. ;;
  203. ;;      vip-insert-intercept-minor-mode
  204. ;;      vip-insert-local-user-minor-mode
  205. ;;      vip-insert-global-user-minor-mode
  206. ;;      vip-insert-kbd-minor-mode
  207. ;;      vip-insert-state-modifier-minor-mode
  208. ;;      vip-insert-diehard-minor-mode
  209. ;;      vip-insert-basic-minor-mode
  210. ;;
  211. ;;  As with VI's editing modes, the first mode, vip-insert-intercept-minor-mode
  212. ;;  is used to bind vital keys that are not to be changed by the user.
  213. ;;
  214. ;;  The next mode, vip-insert-local-user-minor-mode, is used to customize
  215. ;;  bindings in the insert state of Viper. The third mode,
  216. ;;  vip-insert-global-user-minor-mode is like
  217. ;;  vip-insert-local-user-minor-mode, except that its bindings are seen in 
  218. ;;  all Viper buffers. As with vip-vi-local-user-minor-mode, its bindings
  219. ;;  should be done via the function vip-add-local-keys. Bindings for
  220. ;;  vip-insert-global-user-minor-mode can be set with the define-key command.
  221. ;;
  222. ;;  The next minor mode, vip-insert-kbd-minor-mode,
  223. ;;  is used for keyboard VI-style macros defined with :map!. 
  224. ;;
  225. ;;  The fifth minor mode, vip-insert-state-modifier-minor-mode, is like
  226. ;;  vip-vi-state-modifier-minor-mode, except that it is used in the Insert
  227. ;;  state; it can be used to modify keys in a mode-specific fashion. 
  228. ;;
  229. ;;  The minor mode vip-insert-diehard-minor-mode is in effect when
  230. ;;  the user wants a high degree of Vi compatibility (a bad idea, really!).
  231. ;;  The last minor mode, vip-insert-basic-minor-mode, is always in effect
  232. ;;  when Viper is in insert state. It binds a small number of keys needed for
  233. ;;  Viper's operation. 
  234. ;;
  235. ;;  Finally, Viper provides minor modes for overriding bindings set by Emacs
  236. ;;  modes when Viper is in Emacs state:
  237. ;;
  238. ;;     vip-emacs-local-user-minor-mode
  239. ;;      vip-emacs-global-user-minor-mode
  240. ;;      vip-emacs-kbd-minor-mode
  241. ;;      vip-emacs-state-modifier-minor-mode
  242. ;;
  243. ;;  These minor modes are in effect when Viper is in Emacs state. The keymap
  244. ;;  associated with vip-emacs-global-user-minor-mode,
  245. ;;  vip-emacs-global-user-map, overrides the global and local keymaps as
  246. ;;  well as the minor mode keymaps set by other modes. The keymap of
  247. ;;  vip-emacs-local-user-minor-mode, vip-emacs-local-user-map, overrides
  248. ;;  everything, but it is used on a per buffer basis.
  249. ;;  The keymap associated with vip-emacs-state-modifier-minor-mode
  250. ;;  overrides keys on a per-major-mode basis. The mode
  251. ;;  vip-emacs-kbd-minor-mode is used to define Vi-style macros in Emacs
  252. ;;  state.
  253. ;;
  254. ;;  3. There is also one minor mode that is used when Viper is in its
  255. ;;     replace-state (used for commands like cw, C, etc.). This mode is
  256. ;;     called
  257. ;;
  258. ;;       vip-replace-minor-mode
  259. ;;
  260. ;;     and its keymap is vip-replace-map. Replace minor mode is always
  261. ;;     used in conjunction with the minor modes for insert-state, and its
  262. ;;     keymap overshadows the keymaps for insert minor modes.
  263. ;;
  264. ;;  4. Defining buffer-local bindings in Vi and Insert modes. 
  265. ;;  As mentioned before, sometimes, it is convenient to have
  266. ;;  buffer-specific of mode-specific key bindings in Vi and insert modes.
  267. ;;  Viper provides a special function, vip-add-local-keys, to do precisely
  268. ;;  this. For instance, is you need to add couple of mode-specific bindings
  269. ;;  to Insert mode, you can put 
  270. ;;
  271. ;;       (vip-add-local-keys 'insert-state '((key1 . func1) (key2 .func2))) 
  272. ;;
  273. ;;  somewhere in a hook of this major mode. If you put something like this
  274. ;;  in your own elisp function, this will define bindings specific to the
  275. ;;  buffer that was current at the time of the call to vip-add-local-keys.
  276. ;;  The only thing to make sure here is that the major mode of this buffer
  277. ;;  is written according to Emacs conventions, which includes a call to
  278. ;;  (kill-all-local-variables). See vip-add-local-keys for more details.
  279. ;;
  280. ;;
  281. ;;  TO DO (volunteers?):
  282. ;;
  283. ;; 1. Some of the code that is inherited from VIP-3.5 is rather
  284. ;;    convoluted. Instead of vip-command-argument, keymaps should bind the
  285. ;;    actual commands. E.g., "dw" should be bound to a generic command
  286. ;;    vip-delete that will delete things based on the value of
  287. ;;    last-command-char. This would greatly simplify the logic and the code.
  288. ;;
  289. ;; 2. Somebody should venture to write a customization package a la
  290. ;;    options.el that would allow the user to change values of variables
  291. ;;    that meet certain specs (e.g., match a regexp) and whose doc string
  292. ;;    starts with a '*'. Then, the user should be offered to save
  293. ;;    variables that were changed. This will make user's customization job
  294. ;;    much easier.
  295. ;;
  296.  
  297. ;; Code
  298.  
  299. (require 'advice)
  300. (require 'cl)
  301. (require 'ring)
  302.  
  303. (require 'viper-util)
  304.  
  305. ;; Compiler pacifier
  306. (defvar vip-minibuffer-current-face)
  307. (defvar vip-minibuffer-insert-face)
  308. (defvar vip-minibuffer-vi-face)
  309. (defvar vip-minibuffer-emacs-face)
  310. (defvar iso-accents-mode)
  311. (defvar zmacs-region-stays)
  312. ;; end pacifier
  313.  
  314.  
  315. ;;; Variables
  316.           
  317. ;; Is t until viper-mode executes for the very first time. 
  318. ;; Prevents recursive descend into startup messages.
  319. (defvar vip-first-time t)
  320.  
  321. (defvar vip-expert-level 0
  322.   "User's expert level.
  323. The minor mode vip-vi-diehard-minor-mode is in effect when
  324. vip-expert-level is 1 or 2 or when vip-want-emacs-keys-in-vi is t.
  325. The minor mode vip-insert-diehard-minor-mode is in effect when
  326. vip-expert-level is 1 or 2 or if vip-want-emacs-keys-in-insert is t.
  327. Use `M-x vip-set-expert-level' to change this.")
  328.  
  329. ;; Max expert level supported by Viper. This is NOT a user option.
  330. ;; It is here to make it hard for the user from resetting it.
  331. (defconst vip-max-expert-level 5)
  332.  
  333. ;; Contains user settings for vars affected by vip-set-expert-level function.
  334. ;; Not a user option.
  335. (defvar vip-saved-user-settings nil)
  336.            
  337.  
  338. ;;; Viper minor modes
  339.  
  340. ;; This is not local in Emacs, so we make it local.
  341. (make-variable-buffer-local 'minor-mode-map-alist)
  342.  
  343. ;; Mode for vital things like \e, C-z.
  344. (vip-deflocalvar vip-vi-intercept-minor-mode nil)
  345.  
  346. (vip-deflocalvar vip-vi-basic-minor-mode nil
  347.   "Viper's minor mode for Vi bindings.")
  348.   
  349. (vip-deflocalvar vip-vi-local-user-minor-mode nil
  350.   "Auxiliary minor mode for user-defined local bindings in Vi state.")
  351.  
  352. (vip-deflocalvar vip-vi-global-user-minor-mode nil
  353.   "Auxiliary minor mode for user-defined global bindings in Vi state.")
  354.  
  355. (vip-deflocalvar vip-vi-state-modifier-minor-mode nil
  356.   "Minor mode used to make major-mode-specific modification to Vi state.")
  357.  
  358. (vip-deflocalvar vip-vi-diehard-minor-mode nil
  359.   "This minor mode is in effect when the user wants Viper to be Vi.")
  360.  
  361. (vip-deflocalvar vip-vi-kbd-minor-mode nil
  362.   "Minor mode for Ex command macros in Vi state.
  363. The corresponding keymap stores key bindings of Vi macros defined with
  364. the Ex command :map.")
  365.  
  366. ;; Mode for vital things like \e, C-z.
  367. (vip-deflocalvar vip-insert-intercept-minor-mode nil)
  368.  
  369. (vip-deflocalvar vip-insert-basic-minor-mode nil
  370.   "Viper's minor mode for bindings in Insert mode.")
  371.  
  372. (vip-deflocalvar vip-insert-local-user-minor-mode nil
  373.   "Auxiliary minor mode for buffer-local user-defined bindings in Insert state.
  374. This is a way to overshadow normal Insert mode bindings locally to certain
  375. designated buffers.")
  376.  
  377. (vip-deflocalvar vip-insert-global-user-minor-mode nil
  378.   "Auxiliary minor mode for global user-defined bindings in Insert state.")
  379.  
  380. (vip-deflocalvar vip-insert-state-modifier-minor-mode nil
  381.   "Minor mode used to make major-mode-specific modification to Insert state.")
  382.  
  383. (vip-deflocalvar vip-insert-diehard-minor-mode nil
  384.   "Minor mode that simulates Vi very closely.
  385. Not recommened, except for the novice user.")
  386.  
  387. (vip-deflocalvar vip-insert-kbd-minor-mode nil
  388. "Minor mode for Ex command macros Insert state.
  389. The corresponding keymap stores key bindings of Vi macros defined with
  390. the Ex command :map!.")
  391.  
  392. (vip-deflocalvar vip-replace-minor-mode nil
  393.   "Minor mode in effect in replace state (cw, C, and the like commands).")
  394.  
  395. ;; Mode for vital things like \C-z and \C-x)
  396. ;; This is t, by default. So, any new buffer will have C-z defined as
  397. ;; switch to Vi, unless we switched states in this buffer
  398. (vip-deflocalvar vip-emacs-intercept-minor-mode t)
  399.   
  400. (vip-deflocalvar vip-emacs-local-user-minor-mode t
  401.   "Minor mode for local user bindings effective in Emacs state.
  402. Users can use it to override Emacs bindings when Viper is in its Emacs
  403. state.")  
  404.   
  405. (vip-deflocalvar vip-emacs-global-user-minor-mode t
  406.   "Minor mode for global user bindings in effect in Emacs state.
  407. Users can use it to override Emacs bindings when Viper is in its Emacs
  408. state.")  
  409.  
  410. (vip-deflocalvar vip-emacs-kbd-minor-mode t
  411.   "Minor mode for Vi style macros in Emacs state.
  412. The corresponding keymap stores key bindings of Vi macros defined with
  413. `vip-record-kbd-macro' command. There is no Ex-level command to do this
  414. interactively.")
  415.  
  416. (vip-deflocalvar vip-emacs-state-modifier-minor-mode t
  417.   "Minor mode used to make major-mode-specific modification to Emacs state.
  418. For instance, a Vi purist may want to bind `dd' in Dired mode to a function
  419. that deletes a file.")
  420.  
  421.  
  422.  
  423. ;;; ISO characters
  424.   
  425. (vip-deflocalvar vip-automatic-iso-accents nil
  426.   "*If non-nil, ISO accents will be turned on in insert/replace emacs states and turned off in vi-state. 
  427. For some users, this behavior may be too primitive. In this case, use
  428. insert/emacs/vi state hooks.")
  429.   
  430.   
  431. ;;; Emacs keys in other states.  
  432.  
  433. (defvar vip-want-emacs-keys-in-insert t
  434.   "*Set to nil if you want complete Vi compatibility in insert mode.
  435. Complete compatibility with Vi is not recommended for power use of Viper.")
  436.  
  437. (defvar vip-want-emacs-keys-in-vi t
  438.   "*Set to nil if you want complete Vi compatibility in Vi mode.
  439. Full Vi compatibility is not recommended for power use of Viper.")
  440.  
  441.  
  442.  
  443. ;; VI-style Undo
  444.  
  445. ;; Used to 'undo' complex commands, such as replace and insert commands.
  446. (vip-deflocalvar vip-undo-needs-adjustment nil)
  447. (put 'vip-undo-needs-adjustment 'permanent-local t)
  448.  
  449. ;; A mark that Viper puts on buffer-undo-list.  Marks the beginning of a
  450. ;; complex command that must be undone atomically. If inserted, it is
  451. ;; erased by vip-change-state-to-vi and vip-repeat.
  452. (defconst vip-buffer-undo-list-mark 'viper)
  453.  
  454. (defvar vip-keep-point-on-undo nil
  455.   "*Non-nil means not to move point while undoing commands.
  456. This style is different from Emacs and Vi. Try it to see if
  457. it better fits your working style.")  
  458.  
  459. ;; Replace mode and changing text
  460.  
  461. ;; Viper's own after/before change functions, which get vip-add-hook'ed to
  462. ;; Emacs's
  463. (vip-deflocalvar vip-after-change-functions nil "")
  464. (vip-deflocalvar vip-before-change-functions nil "")
  465. (vip-deflocalvar vip-post-command-hooks nil "")
  466. (vip-deflocalvar vip-pre-command-hooks nil "")
  467.  
  468. ;; Can be used to pass global states around for short period of time
  469. (vip-deflocalvar vip-intermediate-command nil "")
  470.  
  471. ;; Indicates that the current destructive command has started in replace mode.
  472. (vip-deflocalvar vip-began-as-replace nil "")
  473.  
  474. (defvar vip-replace-overlay-cursor-color "Red"
  475.   "*Cursor color to use in Replace state")
  476.  
  477.   
  478. (vip-deflocalvar vip-replace-overlay nil "")
  479. (put 'vip-replace-overlay 'permanent-local t)
  480.  
  481. (if (vip-has-face-support-p)
  482.     (progn
  483.       (make-face 'vip-replace-overlay-face)
  484.       (vip-hide-face 'vip-replace-overlay-face)
  485.       (or (face-differs-from-default-p 'vip-replace-overlay-face)
  486.       (progn
  487.         (if (vip-can-use-colors "darkseagreen2" "Black")
  488.         (progn
  489.           (set-face-background
  490.            'vip-replace-overlay-face "darkseagreen2")
  491.           (set-face-foreground 'vip-replace-overlay-face "Black")))
  492.         (set-face-underline-p 'vip-replace-overlay-face t))
  493.       )))
  494.         
  495. (defvar vip-replace-overlay-face 'vip-replace-overlay-face
  496.   "*Face for highlighting replace regions on a window display.")
  497.   
  498. (defvar vip-replace-region-end-delimiter "$"
  499.   "A string marking the end of replacement regions.
  500. It is used only with TTYs or if `vip-use-replace-region-delimiters'
  501. is non-nil.")
  502. (defvar vip-replace-region-start-delimiter ""
  503.   "A string marking the beginning of replacement regions.
  504. It is used only with TTYs or if `vip-use-replace-region-delimiters'
  505. is non-nil.")
  506. (defvar vip-use-replace-region-delimiters 
  507.   (or (not (vip-has-face-support-p)) (not (vip-color-display-p)))
  508.   "*If non-nil, Viper will always use `vip-replace-region-end-delimiter' and
  509. `vip-replace-region-start-delimiter' to delimit replacement regions, even on
  510. color displays. By default, the delimiters are used only on TTYs or
  511. monochrome displays.")
  512.   
  513. ;; XEmacs requires glyphs
  514. (if vip-xemacs-p
  515.     (progn
  516.       (or (glyphp vip-replace-region-end-delimiter)
  517.       (setq vip-replace-region-end-delimiter
  518.         (make-glyph vip-replace-region-end-delimiter)))
  519.       (or (glyphp vip-replace-region-start-delimiter)
  520.       (setq vip-replace-region-start-delimiter
  521.         (make-glyph vip-replace-region-start-delimiter)))
  522.       ))
  523.       
  524.   
  525. ;; These are local marker that must be initialized to nil and moved with
  526. ;; `vip-move-marker-locally'
  527. ;;
  528. ;; Remember the last position inside the replace region.
  529. (vip-deflocalvar vip-last-posn-in-replace-region nil)
  530. ;; Remember the last position while inserting
  531. (vip-deflocalvar vip-last-posn-while-in-insert-state nil)
  532. (put 'vip-last-posn-in-replace-region 'permanent-local t)
  533. (put 'vip-last-posn-while-in-insert-state 'permanent-local t)
  534.  
  535. (vip-deflocalvar vip-sitting-in-replace nil "")
  536. (put 'vip-sitting-in-replace 'permanent-local t)
  537.   
  538. ;; Remember the number of characters that have to be deleted in replace
  539. ;; mode to compensate for the inserted characters.
  540. (vip-deflocalvar vip-replace-chars-to-delete 0 "")
  541. (vip-deflocalvar vip-replace-chars-deleted 0 "")
  542.  
  543. ;; Insertion ring and command ring
  544. (defvar vip-insertion-ring-size 14
  545.   "The size of the insertion ring.")
  546. ;; The insertion ring.
  547. (defvar vip-insertion-ring nil)
  548. ;; This is temp insertion ring. Used to do rotation for display purposes.
  549. ;; When rotation just started, it is initialized to vip-insertion-ring.
  550. (defvar vip-temp-insertion-ring nil)
  551. (defvar vip-last-inserted-string-from-insertion-ring "")
  552.  
  553. (defvar vip-command-ring-size 14
  554.   "The size of the command ring.")
  555. ;; The command ring.
  556. (defvar vip-command-ring nil)
  557. ;; This is temp command ring. Used to do rotation for display purposes.
  558. ;; When rotation just started, it is initialized to vip-command-ring.
  559. (defvar vip-temp-command-ring nil)
  560.  
  561. ;; Modes and related variables
  562.  
  563. ;; Current mode.  One of: `emacs-state', `vi-state', `insert-state'
  564. (vip-deflocalvar vip-current-state 'emacs-state)
  565.  
  566.  
  567. (defvar vip-toggle-key "\C-z"
  568.   "The key used to change states from emacs to Vi and back.
  569. In insert mode, this key also functions as Meta. 
  570. Must be set in .vip file or prior to loading Viper.
  571. This setting cannot be changed interactively.")
  572.  
  573. (defvar vip-ESC-key "\e" 
  574.   "Key used to ESC. 
  575. Must be set in .vip file or prior to loading Viper.
  576. This setting cannot be changed interactively.")
  577.  
  578. (defvar vip-no-multiple-ESC  t
  579.   "*If true, multiple ESC in Vi mode will cause bell to ring.
  580. \_ is then mapped to Meta.
  581. This is set to t on a windowing terminal and to 'twice on a dumb
  582. terminal (unless the user level is 1, 2, or 5). On a dumb terminal, this
  583. enables cursor keys and is generally more convenient, as terminals usually
  584. don't have a convenient Meta key.
  585. Setting vip-no-multiple-ESC to nil will allow as many multiple ESC,
  586. as is allowed by the major mode in effect.") 
  587.  
  588.  
  589. (defvar vip-want-ctl-h-help nil
  590.   "*If t then C-h is bound to help-command in insert mode, if nil then it is
  591. bound to delete-backward-char.")
  592.  
  593. ;; Autoindent in insert
  594.  
  595. ;; Variable that keeps track of whether C-t has been pressed.
  596. (vip-deflocalvar vip-cted nil "")
  597.  
  598. ;; Preserve the indent value, used by C-d in insert mode.
  599. (vip-deflocalvar vip-current-indent 0)
  600.  
  601. ;; Whether to preserve the indent, used by C-d in insert mode.
  602. (vip-deflocalvar vip-preserve-indent nil)
  603.  
  604. (vip-deflocalvar vip-auto-indent nil
  605.   "*Autoindent if t.")
  606. (vip-deflocalvar vip-electric-mode t
  607.   "*If t, enable electric behavior. 
  608. Currently only enables auto-indentation `according to mode'.")
  609.  
  610. (defconst vip-shift-width 8
  611.   "*The shiftwidth variable.")
  612.  
  613. ;; Variables for repeating destructive commands
  614.  
  615. (defconst vip-keep-point-on-repeat t
  616.   "*If t, don't move point when repeating previous command.
  617. This is useful for doing repeated changes with the '.' key.
  618. The user can change this to nil, if she likes when the cursor moves
  619. to a new place after repeating previous Vi command.") 
  620.  
  621. ;; Remember insert point as a marker.  This is a local marker that must be
  622. ;; initialized to nil and moved with `vip-move-marker-locally'.
  623. (vip-deflocalvar vip-insert-point nil)
  624. (put 'vip-insert-point 'permanent-local t)
  625.  
  626. ;; This remembers the point before dabbrev-expand was called.
  627. ;; If vip-insert-point turns out to be bigger than that, it is reset
  628. ;; back to vip-pre-command-point.
  629. ;; The reason this is needed is because dabbrev-expand (and possibly
  630. ;; others) may jump to before the insertion point, delete something and
  631. ;; then reinsert a bigger piece. For instance:  bla^blo
  632. ;; If dabbrev-expand is called after `blo' and ^ undicates vip-insert-point,
  633. ;; then point jumps to the beginning of `blo'. If expansion is found, `blablo'
  634. ;; is deleted, and we have |^, where | denotes point. Next, dabbrev-expand
  635. ;; will insert the expansion, and we get: blablo^
  636. ;; Whatever we insert next goes before the ^, i.e., before the
  637. ;; vip-insert-point marker. So, Viper will think that nothing was
  638. ;; inserted. Remembering the orig position of the marker circumvents the
  639. ;; problem.
  640. ;; We don't know of any command, except dabbrev-expand, that has the same
  641. ;; problem. However, the same trick can be used if such a command is
  642. ;; discovered later.
  643. ;;
  644. (vip-deflocalvar vip-pre-command-point nil)
  645. (put 'vip-pre-command-point 'permanent-local t) ; this is probably an overkill
  646.  
  647. ;; This is used for saving inserted text.
  648. (defvar vip-last-insertion  nil)
  649.   
  650. ;; Remembers the last replaced region.
  651. (defvar vip-last-replace-region "")
  652.   
  653. ;; Remember com point as a marker.
  654. ;; This is a local marker. Should be moved with `vip-move-marker-locally'
  655. (vip-deflocalvar vip-com-point nil)
  656.  
  657. ;; If non-nil, the value is a list (M-COM VAL COM REG inserted-text cmd-keys)
  658. ;; It is used to re-execute last destructive command.
  659. ;; M-COM is a Lisp symbol representing the function to be executed.
  660. ;; VAL is the prefix argument that was used with that command.
  661. ;; COM is an internal descriptor, such as ?r, ?c, ?C, which contains
  662. ;; additional information on how the function in M-COM is to be handled.
  663. ;; REG is the register used by command
  664. ;; INSERTED-TEXT is text inserted by that command (in case of o, c, C, i, r
  665. ;; commands).
  666. ;; COMMAND-KEYS are the keys that were typed to invoke the command.
  667. (defvar vip-d-com nil)
  668.  
  669. ;; The character remembered by the Vi `r' command.
  670. (defvar vip-d-char nil)
  671.  
  672. ;; Name of register to store deleted or yanked strings
  673. (defvar vip-use-register nil)
  674.  
  675.  
  676.  
  677. ;; Variables for Moves and Searches
  678.  
  679. ;; For use by `;' command.
  680. (defvar vip-f-char nil)
  681.  
  682. ;; For use by `.' command.
  683. (defvar vip-F-char nil)
  684.  
  685. ;; For use by `;' command.
  686. (defvar vip-f-forward nil)
  687.  
  688. ;; For use by `;' command.
  689. (defvar vip-f-offset nil)
  690.  
  691. ;; Last search string
  692. (defvar vip-s-string "")
  693.  
  694. (defvar vip-quote-string "> "
  695.   "String inserted at the beginning of quoted region.")
  696.  
  697. ;; If t, search is forward.
  698. (defvar vip-s-forward nil)
  699.  
  700. (defconst vip-case-fold-search nil
  701.   "*If t, search ignores cases.")
  702.  
  703. (defconst vip-re-search t
  704.   "*If t, search is reg-exp search, otherwise vanilla search.")
  705.  
  706. (defconst vip-re-query-replace t
  707.   "*If t then do regexp replace, if nil then do string replace.")
  708.  
  709. (defconst vip-re-replace t
  710.   "*If t, do regexp replace. nil means do string replace.")
  711.  
  712. (vip-deflocalvar vip-ex-style-motion t
  713.   "*Ex-style: the commands l,h do not cross lines, etc.")
  714.  
  715. (vip-deflocalvar vip-ex-style-editing-in-insert t
  716.   "*The keys ^H, ^? don't jump lines in insert, ESC moves cursor back, etc.
  717. Note: this doesn't preclude ^H and ^? from deleting characters by moving
  718. past the insertion point. This is a feature, not a bug. ")
  719.  
  720. (vip-deflocalvar vip-delete-backwards-in-replace nil
  721.   "*If t, DEL key will delete characters while moving the cursor backwards.
  722. If nil, the cursor will move backwards without deleting anything.")
  723.  
  724. (defconst vip-buffer-search-char nil
  725.   "*Key bound for buffer-searching.")
  726.  
  727. (defconst vip-search-wrap-around-t t
  728.   "*If t, search wraps around.")
  729.   
  730. (vip-deflocalvar vip-related-files-and-buffers-ring nil
  731.   "*Ring of file and buffer names that are considered to be related to the
  732. current buffer.
  733. These buffers can be cycled through via :R and :P commands.")
  734. (put 'vip-related-files-and-buffers-ring 'permanent-local t)
  735.  
  736. ;; Used to find out if we are done with searching the current buffer.
  737. (vip-deflocalvar vip-local-search-start-marker nil)
  738. ;; As above, but global
  739. (defvar vip-search-start-marker (make-marker))
  740.  
  741. ;; the search overlay
  742. (vip-deflocalvar vip-search-overlay nil)
  743.  
  744.  
  745. (defvar vip-heading-start 
  746.   (concat "^\\s-*(\\s-*defun\\s-\\|"                    ; lisp
  747.       "^{\\s-*$\\|^[_a-zA-Z][^()]*[()].*{\\s-*$\\|"            ; C/C++
  748.       "^\\s-*class.*{\\|^\\s-*struct.*{\\|^\\s-*enum.*{\\|"
  749.       "^\\\\[sb][a-z]*{.*}\\s-*$\\|"                ; latex
  750.       "^@node\\|@table\\|^@m?enu\\|^@itemize\\|^@if\\|"    ; texinfo
  751.       "^.+:-")                                    ; prolog
  752.   "*Regexps for Headings. Used by \[\[ and \]\].")
  753.  
  754. (defvar vip-heading-end 
  755.   (concat "^}\\|"                        ; C/C++
  756.       "^\\\\end{\\|"                    ; latex
  757.       "^@end \\|"                        ; texinfo
  758.       ")\n\n[ \t\n]*\\|"                    ; lisp
  759.       "\\.\\s-*$")                        ; prolog
  760.       "*Regexps to end Headings/Sections. Used by \[\].")
  761.  
  762.  
  763. ;; These two vars control the interaction of jumps performed by ' and `.
  764. ;; In this new version, '' doesn't erase the marks set by ``, so one can
  765. ;; use both kinds of jumps interchangeably and without loosing positions
  766. ;; inside the lines.
  767.  
  768. ;; Remembers position of the last jump done using ``'.
  769. (vip-deflocalvar vip-last-jump  nil)
  770. ;; Remembers position of the last jump done using `''.
  771. (vip-deflocalvar vip-last-jump-ignore 0)
  772.  
  773. ;; Some common error messages
  774.  
  775. (defconst vip-SpuriousText "Spurious text after command"  "")
  776. (defconst vip-BadExCommand "Not an editor command"   "")
  777. (defconst vip-InvalidCommandArgument "Invalid command argument"   "")
  778. (defconst vip-NoPrevSearch "No previous search string"   "")
  779. (defconst vip-EmptyRegister "`%c': Nothing in this register"   "")
  780. (defconst vip-InvalidRegister "`%c': Invalid register"   "")
  781. (defconst vip-EmptyTextmarker "`%c': Text marker doesn't point anywhere"   "")
  782. (defconst vip-InvalidTextmarker "`%c': Invalid text marker"   "")
  783. (defconst vip-InvalidViCommand "Invalid command"   "")
  784. (defconst vip-BadAddress "Ill-formed address"   "")
  785. (defconst vip-FirstAddrExceedsSecond "First address exceeds second"   "")
  786. (defconst vip-NoFileSpecified "No file specified"   "")
  787.  
  788.  
  789. ;; History variables
  790.  
  791. ;; History of search strings.
  792. (defvar vip-search-history  (list ""))
  793. ;; History of query-replace strings used as a source.
  794. (defvar vip-replace1-history nil)
  795. ;; History of query-replace strings used as replacement.
  796. (defvar vip-replace2-history nil)
  797. ;; History of region quoting strings.
  798. (defvar vip-quote-region-history (list vip-quote-string))
  799. ;; History of Ex-style commands.
  800. (defvar vip-ex-history nil)
  801. ;; History of shell commands.
  802. (defvar vip-shell-history nil)
  803.  
  804.  
  805. ;; Last shell command. There are two of these, one for Ex (in viper-ex)
  806. ;; and one for Vi.
  807.  
  808. ;; Last shell command executed with ! command.
  809. (defvar vip-last-shell-com nil)
  810.  
  811.  
  812.  
  813. ;;; Miscellaneous
  814.  
  815. ;; don't bark when mark is inactive
  816. (setq mark-even-if-inactive t)
  817.  
  818. (defvar vip-inhibit-startup-message nil
  819.   "Whether Viper startup message should be inhibited.")
  820.  
  821. (defvar vip-always t
  822.   "t means, arrange that vi-state will be a default.")
  823.  
  824. (defvar vip-custom-file-name (cond (vip-vms-os-p "sys$login:.vip")
  825.                    ((memq system-type '(emx ms-dos))
  826.                     "/_vip")
  827.                    ((memq system-type '(windows-nt windows-95))
  828.                     "~/_vip")
  829.                    (t ; Unix
  830.                     "~/.vip"))
  831.   "Viper customisation file.
  832. This variable must be set _before_ loading Viper.")
  833.  
  834.  
  835. (defvar vip-spell-function 'ispell-region
  836.   "Spell function used by #s<move> command to spell.")
  837.  
  838. (defvar vip-tags-file-name "TAGS"
  839.   "The tags file used by Viper.")
  840.  
  841. ;; Minibuffer
  842.  
  843. (defvar vip-vi-style-in-minibuffer t
  844.   "If t, use vi-style editing in minibuffer.
  845. Should be set in `~/.vip' file.")
  846.   
  847. ;; overlay used in the minibuffer to indicate which state it is in
  848. (vip-deflocalvar vip-minibuffer-overlay nil)
  849.  
  850. ;; Hook, specific to Viper, which is run just *before* exiting the minibuffer.
  851. ;; Beginning with Emacs 19.26, the standard `minibuffer-exit-hook' is run
  852. ;; *after* exiting the minibuffer
  853. (defvar vip-minibuffer-exit-hook nil)
  854.  
  855. (vip-deflocalvar vip-vi-minibuffer-minor-mode nil
  856.    "Minor mode that forces Vi-style when the Minibuffer is in Vi state.")
  857. (vip-deflocalvar vip-insert-minibuffer-minor-mode nil
  858.    "Minor mode that forces Vi-style when the Minibuffer is in Insert state.")
  859.   
  860. ;; setup emacs-supported vi-style feel
  861. (setq next-line-add-newlines nil
  862.       require-final-newline t)
  863.  
  864. (make-variable-buffer-local 'require-final-newline)
  865.        
  866.  
  867. ;; Mode line
  868. (defconst vip-vi-state-id      "<V> "
  869.   "Mode line tag identifying the Vi mode of Viper.")
  870. (defconst vip-emacs-state-id    "<E> "
  871.   "Mode line tag identifying the Emacs mode of Viper.")
  872. (defconst vip-insert-state-id    "<I> "
  873.   "Mode line tag identifying the Insert mode of Viper.")
  874. (defconst vip-replace-state-id    "<R> "
  875.   "Mode line tag identifying the Replace mode of Viper.")
  876.  
  877. ;; Viper changes the default mode-line-buffer-identification
  878. (setq-default mode-line-buffer-identification '(" %b"))
  879.  
  880. ;; Variable displaying the current Viper state in the mode line.
  881. (vip-deflocalvar vip-mode-string vip-emacs-state-id)
  882. (or (memq 'vip-mode-string global-mode-string)
  883.     (setq global-mode-string
  884.       (append '("" vip-mode-string) (cdr global-mode-string))))
  885.  
  886.  
  887. (defvar vip-vi-state-hook nil
  888.   "*Hooks run just before the switch to Vi mode is completed.")
  889. (defvar vip-insert-state-hook nil
  890.   "*Hooks run just before the switch to Insert mode is completed.")
  891. (defvar vip-replace-state-hook nil
  892.   "*Hooks run just before the switch to Replace mode is completed.")
  893. (defvar vip-emacs-state-hook nil
  894.   "*Hooks run just before the switch to Emacs mode is completed.")
  895.   
  896. (defvar vip-load-hook nil
  897.   "Hooks run just after loading Viper.")
  898.   
  899.  
  900. ;; Generic predicates
  901.  
  902. ;; These test functions are shamelessly lifted from vip 4.4.2 by Aamod Sane
  903.  
  904. ;; generate test functions
  905. ;; given symbol foo, foo-p is the test function, foos is the set of
  906. ;; Viper command keys
  907. ;; (macroexpand '(vip-test-com-defun foo))
  908. ;; (defun foo-p (com) (consp (memq (if (< com 0) (- com) com) foos)))
  909.  
  910. (defmacro vip-test-com-defun (name)
  911.   (let* ((snm (symbol-name name))
  912.      (nm-p (intern (concat snm "-p")))
  913.      (nms (intern (concat snm "s"))))
  914.     (` (defun (, nm-p) (com) 
  915.      (consp (memq (if (< com 0) (- com) com) (, nms)))))))
  916.   
  917. ;; Variables for defining VI commands
  918.  
  919. ;; Modifying commands that can be prefixes to movement commands
  920. (defconst vip-prefix-commands '(?c ?d ?y ?! ?= ?# ?< ?> ?\"))
  921. (vip-test-com-defun vip-prefix-command)
  922.   
  923. ;; Commands that are pairs eg. dd. r and R here are a hack
  924. (defconst vip-charpair-commands '(?c ?d ?y ?! ?= ?< ?> ?r ?R))
  925. (vip-test-com-defun vip-charpair-command)
  926.  
  927. (defconst vip-movement-commands '(?b ?B ?e ?E ?f ?F ?G ?h ?H ?j ?k ?l
  928.                      ?H ?M ?n ?t ?T ?w ?W ?$ ?%
  929.                      ?^ ?( ?) ?- ?+ ?| ?{ ?} ?[ ?] ?' ?`
  930.                      ?; ?, ?0 ?? ?/
  931.                      )
  932.                      "Movement commands")
  933. (vip-test-com-defun vip-movement-command)
  934.  
  935. ;; Commands that can be repeated by .(dotted)
  936. (defconst vip-dotable-commands '(?c ?d ?C ?D ?> ?<))
  937. (vip-test-com-defun vip-dotable-command)
  938.  
  939. ;; Commands that can follow a #
  940. (defconst vip-hash-cmds '(?c ?C ?g ?q ?S))
  941. (vip-test-com-defun vip-hash-cmd)
  942.  
  943. ;; Commands that may have registers as prefix
  944. (defconst vip-regsuffix-commands '(?d ?y ?Y ?D ?p ?P ?x ?X))
  945. (vip-test-com-defun vip-regsuffix-command)
  946.  
  947.  
  948.  
  949. ;;; Arrange the keymaps
  950. (require 'viper-keym)
  951.  
  952.  
  953. ;;; CODE
  954.  
  955. ;; sentinels
  956.  
  957. ;; Runs vip-after-change-functions inside after-change-functions
  958. (defun vip-after-change-sentinel (beg end len)
  959.   (let ((list vip-after-change-functions))
  960.     (while list
  961.       (funcall (car list) beg end len)
  962.       (setq list (cdr list)))))
  963.       
  964. ;; Runs vip-before-change-functions inside before-change-functions
  965. (defun vip-before-change-sentinel (beg end)
  966.   (let ((list vip-before-change-functions))
  967.     (while list
  968.       (funcall (car list) beg end)
  969.       (setq list (cdr list)))))
  970.  
  971. (defsubst vip-post-command-sentinel ()
  972.   (run-hooks 'vip-post-command-hooks))
  973.   
  974. (defsubst vip-pre-command-sentinel ()
  975.   (run-hooks 'vip-pre-command-hooks))
  976.   
  977. ;; Needed so that Viper will be able to figure the last inserted
  978. ;; chunk of text with reasonable accuracy.
  979. (defsubst vip-insert-state-post-command-sentinel ()
  980.   (if (and (memq vip-current-state '(insert-state replace-state))
  981.        vip-insert-point
  982.        (>= (point) vip-insert-point))
  983.       (setq vip-last-posn-while-in-insert-state (point-marker)))
  984.   (if (and (eq this-command 'dabbrev-expand)
  985.        (integerp vip-pre-command-point)
  986.        (> vip-insert-point vip-pre-command-point))
  987.       (move-marker vip-insert-point vip-pre-command-point))
  988.   )
  989.   
  990. (defsubst vip-insert-state-pre-command-sentinel ()
  991.   (if (and (eq this-command 'dabbrev-expand)
  992.        (markerp vip-insert-point)
  993.        (marker-position vip-insert-point))
  994.       (setq vip-pre-command-point (marker-position vip-insert-point))))
  995.     
  996. (defsubst vip-R-state-post-command-sentinel ()
  997.   ;; Restoring cursor color is needed despite
  998.   ;; vip-replace-state-pre-command-sentinel: When you jump to another buffer in
  999.   ;; another frame, the pre-command hook won't change cursor color to default
  1000.   ;; in that other frame.  So, if the second frame cursor was red and we set
  1001.   ;; the point outside the replacement region, then the cursor color will
  1002.   ;; remain red. Restoring the default, below, prevents this.
  1003.   (if (and (<= (vip-replace-start) (point))
  1004.        (<=  (point) (vip-replace-end)))
  1005.       (vip-change-cursor-color vip-replace-overlay-cursor-color)
  1006.     (vip-restore-cursor-color)
  1007.     ))
  1008.  
  1009. ;; to speed up, don't change cursor color before self-insert
  1010. ;; and common move commands
  1011. (defsubst vip-replace-state-pre-command-sentinel ()
  1012.   (or (memq this-command '(self-insert-command))
  1013.       (memq (vip-event-key last-command-event)
  1014.         '(up down left right (meta f) (meta b)
  1015.          (control n) (control p) (control f) (control b)))
  1016.       (vip-restore-cursor-color)))
  1017.   
  1018. (defun vip-replace-state-post-command-sentinel ()
  1019.   ;; Restoring cursor color is needed despite
  1020.   ;; vip-replace-state-pre-command-sentinel: When one jumps to another buffer
  1021.   ;; in another frame, the pre-command hook won't change cursor color to
  1022.   ;; default in that other frame.  So, if the second frame cursor was red and
  1023.   ;; we set the point outside the replacement region, then the cursor color
  1024.   ;; will remain red. Restoring the default, below, fixes this problem.
  1025.   ;;
  1026.   ;; We optimize for self-insert-command's here, since they either don't change
  1027.   ;; cursor color or, if they terminate replace mode, the color will be changed
  1028.   ;; in vip-finish-change
  1029.   (or (memq this-command '(self-insert-command))
  1030.       (vip-restore-cursor-color))
  1031.   (cond 
  1032.    ((eq vip-current-state 'replace-state)
  1033.     ;; delete characters to compensate for inserted chars.
  1034.     (let ((replace-boundary (vip-replace-end)))
  1035.       (save-excursion
  1036.     (goto-char vip-last-posn-in-replace-region)
  1037.     (delete-char vip-replace-chars-to-delete)
  1038.     (setq vip-replace-chars-to-delete 0
  1039.           vip-replace-chars-deleted 0)
  1040.     ;; terminate replace mode if reached replace limit
  1041.     (if (= vip-last-posn-in-replace-region 
  1042.            (vip-replace-end))
  1043.         (vip-finish-change vip-last-posn-in-replace-region)))
  1044.       
  1045.       (if (and (<= (vip-replace-start) (point))
  1046.            (<=  (point) replace-boundary))
  1047.       (progn
  1048.         ;; the state may have changed in vip-finish-change above
  1049.         (if (eq vip-current-state 'replace-state)
  1050.         (vip-change-cursor-color vip-replace-overlay-cursor-color))
  1051.         (setq vip-last-posn-in-replace-region (point-marker))))
  1052.       ))
  1053.    
  1054.    (t ;; terminate replace mode if changed Viper states.
  1055.     (vip-finish-change vip-last-posn-in-replace-region))))
  1056.  
  1057.  
  1058. ;; changing mode
  1059.  
  1060. ;; Change state to NEW-STATE---either emacs-state, vi-state, or insert-state.
  1061. (defun vip-change-state (new-state)
  1062.   ;; Keep vip-post/pre-command-hooks fresh.
  1063.   ;; We remove then add vip-post/pre-command-sentinel since it is very
  1064.   ;; desirable that vip-pre-command-sentinel is the last hook and
  1065.   ;; vip-post-command-sentinel is the first hook.
  1066.   (remove-hook 'post-command-hook 'vip-post-command-sentinel)
  1067.   (add-hook 'post-command-hook 'vip-post-command-sentinel)
  1068.   (remove-hook 'pre-command-hook 'vip-pre-command-sentinel)
  1069.   (add-hook 'pre-command-hook 'vip-pre-command-sentinel t)
  1070.   ;; These hooks will be added back if switching to insert/replace mode
  1071.   (vip-remove-hook 'vip-post-command-hooks
  1072.            'vip-insert-state-post-command-sentinel)
  1073.   (vip-remove-hook 'vip-pre-command-hooks
  1074.            'vip-insert-state-pre-command-sentinel)
  1075.   (cond ((eq new-state 'vi-state)
  1076.      (cond ((member vip-current-state '(insert-state replace-state))
  1077.             
  1078.         ;; move vip-last-posn-while-in-insert-state
  1079.         ;; This is a normal hook that is executed in insert/replace
  1080.         ;; states after each command. In Vi/Emacs state, it does
  1081.         ;; nothing. We need to execute it here to make sure that
  1082.         ;; the last posn was recorded when we hit ESC.
  1083.         ;; It may be left unrecorded if the last thing done in
  1084.         ;; insert/repl state was dabbrev-expansion or abbrev
  1085.         ;; expansion caused by hitting ESC
  1086.         (vip-insert-state-post-command-sentinel)
  1087.         
  1088.         (condition-case conds
  1089.             (progn
  1090.               (vip-save-last-insertion
  1091.                vip-insert-point 
  1092.                vip-last-posn-while-in-insert-state)
  1093.               (if vip-began-as-replace
  1094.               (setq vip-began-as-replace nil)
  1095.             ;; repeat insert commands if numerical arg > 1
  1096.             (save-excursion
  1097.               (vip-repeat-insert-command))))
  1098.           (error
  1099.            (vip-message-conditions conds)))
  1100.              
  1101.         (if (> (length vip-last-insertion) 0)
  1102.             (vip-push-onto-ring vip-last-insertion
  1103.                     'vip-insertion-ring))
  1104.         
  1105.         (if vip-ex-style-editing-in-insert
  1106.             (or (bolp) (backward-char 1))))
  1107.            ))
  1108.      
  1109.     ;; insert or replace
  1110.     ((memq new-state '(insert-state replace-state))
  1111.      (if (memq vip-current-state '(emacs-state vi-state))
  1112.          (vip-move-marker-locally 'vip-insert-point (point)))
  1113.      (vip-move-marker-locally 'vip-last-posn-while-in-insert-state (point))
  1114.      (vip-add-hook 'vip-post-command-hooks
  1115.                'vip-insert-state-post-command-sentinel t)
  1116.      (vip-add-hook 'vip-pre-command-hooks
  1117.                'vip-insert-state-pre-command-sentinel t))
  1118.     ) ; outermost cond
  1119.   
  1120.   ;; Nothing needs to be done to switch to emacs mode! Just set some
  1121.   ;; variables, which is already done in vip-change-state-to-emacs!
  1122.  
  1123.   (setq vip-current-state new-state)
  1124.   (vip-normalize-minor-mode-map-alist)
  1125.   (vip-adjust-keys-for new-state)
  1126.   (vip-set-mode-vars-for new-state)
  1127.   (vip-refresh-mode-line)
  1128.   )
  1129.  
  1130.  
  1131.     
  1132. (defun vip-adjust-keys-for (state)
  1133.   "Make necessary adjustments to keymaps before entering STATE."
  1134.   (cond ((memq state '(insert-state replace-state))
  1135.      (if vip-auto-indent
  1136.          (progn
  1137.            (define-key vip-insert-basic-map "\C-m" 'vip-autoindent)
  1138.            (if vip-want-emacs-keys-in-insert
  1139.            ;; expert
  1140.            (define-key vip-insert-basic-map "\C-j" nil)
  1141.          ;; novice
  1142.          (define-key vip-insert-basic-map "\C-j" 'vip-autoindent))))
  1143.             
  1144.      (setq vip-insert-diehard-minor-mode
  1145.            (not vip-want-emacs-keys-in-insert))
  1146.            
  1147.      (if vip-want-ctl-h-help
  1148.          (progn 
  1149.            (define-key vip-insert-basic-map "\C-h" 'help-command)
  1150.            (define-key vip-replace-map "\C-h" 'help-command))
  1151.        (define-key vip-insert-basic-map 
  1152.          "\C-h" 'vip-del-backward-char-in-insert)
  1153.        (define-key vip-replace-map
  1154.          "\C-h" 'vip-del-backward-char-in-replace)))
  1155.              
  1156.     (t
  1157.      (setq vip-vi-diehard-minor-mode (not vip-want-emacs-keys-in-vi))
  1158.      (if vip-want-ctl-h-help
  1159.          (define-key vip-vi-basic-map "\C-h" 'help-command)
  1160.        (define-key vip-vi-basic-map "\C-h" 'vip-backward-char)))
  1161.     ))
  1162.          
  1163.     
  1164. ;; Normalizes minor-mode-map-alist by putting Viper keymaps first.
  1165. ;; This ensures that Viper bindings are in effect, regardless of which minor
  1166. ;; modes were turned on by the user or by other packages.
  1167. (defun vip-normalize-minor-mode-map-alist ()
  1168.   (setq minor-mode-map-alist 
  1169.     (vip-append-filter-alist
  1170.      (list
  1171.            (cons 'vip-vi-intercept-minor-mode vip-vi-intercept-map)
  1172.            (cons 'vip-vi-minibuffer-minor-mode vip-minibuffer-map) 
  1173.            (cons 'vip-vi-local-user-minor-mode vip-vi-local-user-map)
  1174.            (cons 'vip-vi-kbd-minor-mode vip-vi-kbd-map)
  1175.            (cons 'vip-vi-global-user-minor-mode vip-vi-global-user-map)
  1176.            (cons 'vip-vi-state-modifier-minor-mode
  1177.              (if (keymapp
  1178.               (cdr (assoc major-mode vip-vi-state-modifier-alist)))
  1179.              (cdr (assoc major-mode vip-vi-state-modifier-alist))
  1180.                vip-empty-keymap))
  1181.            (cons 'vip-vi-diehard-minor-mode  vip-vi-diehard-map)
  1182.            (cons 'vip-vi-basic-minor-mode     vip-vi-basic-map)
  1183.            (cons 'vip-insert-intercept-minor-mode vip-insert-intercept-map)
  1184.            (cons 'vip-replace-minor-mode  vip-replace-map)
  1185.            ;; vip-insert-minibuffer-minor-mode must come after
  1186.            ;; vip-replace-minor-mode 
  1187.            (cons 'vip-insert-minibuffer-minor-mode
  1188.              vip-minibuffer-map) 
  1189.            (cons 'vip-insert-local-user-minor-mode
  1190.              vip-insert-local-user-map)
  1191.            (cons 'vip-insert-kbd-minor-mode vip-insert-kbd-map)
  1192.            (cons 'vip-insert-global-user-minor-mode
  1193.              vip-insert-global-user-map)
  1194.            (cons 'vip-insert-state-modifier-minor-mode
  1195.              (if (keymapp
  1196.               (cdr
  1197.                (assoc major-mode vip-insert-state-modifier-alist)))
  1198.              (cdr
  1199.               (assoc major-mode vip-insert-state-modifier-alist))
  1200.                vip-empty-keymap))
  1201.            (cons 'vip-insert-diehard-minor-mode vip-insert-diehard-map)
  1202.            (cons 'vip-insert-basic-minor-mode vip-insert-basic-map)
  1203.            (cons 'vip-emacs-intercept-minor-mode
  1204.              vip-emacs-intercept-map)
  1205.            (cons 'vip-emacs-local-user-minor-mode
  1206.              vip-emacs-local-user-map)
  1207.            (cons 'vip-emacs-kbd-minor-mode vip-emacs-kbd-map)
  1208.            (cons 'vip-emacs-global-user-minor-mode
  1209.              vip-emacs-global-user-map)
  1210.            (cons 'vip-emacs-state-modifier-minor-mode
  1211.              (if (keymapp
  1212.               (cdr
  1213.                (assoc major-mode vip-emacs-state-modifier-alist)))
  1214.              (cdr
  1215.               (assoc major-mode vip-emacs-state-modifier-alist))
  1216.                vip-empty-keymap))
  1217.            )
  1218.      minor-mode-map-alist)))
  1219.      
  1220.  
  1221.  
  1222.  
  1223.  
  1224. ;; Viper mode-changing commands and utilities
  1225.  
  1226. ;; Modifies mode-line-buffer-identification.
  1227. (defun vip-refresh-mode-line ()
  1228.   (setq vip-mode-string    
  1229.     (cond ((eq vip-current-state 'emacs-state) vip-emacs-state-id)
  1230.           ((eq vip-current-state 'vi-state) vip-vi-state-id)
  1231.           ((eq vip-current-state 'replace-state) vip-replace-state-id)
  1232.           ((eq vip-current-state 'insert-state) vip-insert-state-id)))
  1233.     
  1234.   ;; Sets Viper mode string in global-mode-string
  1235.   (force-mode-line-update))
  1236.   
  1237. ;;;###autoload
  1238. (defun viper-mode ()
  1239.   "Turn on Viper emulation of Vi."
  1240.   (interactive)
  1241.   (if (not noninteractive)
  1242.       (progn
  1243.     (if vip-first-time ; This check is important. Without it, startup and 
  1244.         (progn       ; expert-level msgs mix up when viper-mode recurses
  1245.           (setq vip-first-time nil)
  1246.           (if (not vip-inhibit-startup-message)
  1247.           (save-window-excursion
  1248.             (setq vip-inhibit-startup-message t)
  1249.             (delete-other-windows)
  1250.             (switch-to-buffer "Viper Startup Message")
  1251.             (erase-buffer)
  1252.             (insert
  1253.              (substitute-command-keys
  1254.               "Viper Is a Package for Emacs Rebels.
  1255. It is also a VI Plan for Emacs Rescue and a venomous VI PERil.
  1256.  
  1257. Technically speaking, Viper is a Vi emulation package for GNU Emacs 19 and
  1258. XEmacs 19.  It supports virtually all of Vi and Ex functionality, extending
  1259. and improving upon much of it.
  1260.  
  1261.    1. Viper supports Vi at several levels. Level 1 is the closest to Vi,
  1262.       level 5 provides the most flexibility to depart from many Vi conventions.
  1263.       
  1264.       You will be asked to specify your user level in a following screen.
  1265.    
  1266.       If you select user level 1 then the keys ^X, ^C, ^Z, and ^G will behave
  1267.       as in VI, to smooth transition to Viper for the beginners. However, to
  1268.       use Emacs productively, you are advised to reach user level 3 or higher. 
  1269.       
  1270.       If your user level is 2 or higher, ^X and ^C will invoke Emacs
  1271.       functions,as usual in Emacs; ^Z will toggle vi/emacs modes, and 
  1272.       ^G will be the usual Emacs's keyboard-quit (something like ^C in VI).
  1273.    
  1274.    2. Vi exit functions (e.g., :wq, ZZ) work on INDIVIDUAL files -- they
  1275.       do not cause Emacs to quit, except at user level 1 (a novice).
  1276.    3. ^X^C EXITS EMACS.
  1277.    4. Viper supports multiple undo: `u' will undo. Typing `.' will repeat
  1278.       undo. Another `u' changes direction.
  1279.    
  1280.    6. Emacs Meta functions are invoked by typing `_' or `\\ ESC'.
  1281.       On a window system, the best way is to use the Meta-key.
  1282.    7. Try \\[keyboard-quit] and \\[abort-recursive-edit] repeatedly,if
  1283.       something funny happens. This would abort the current editing command. 
  1284.       
  1285. You can get more information on Viper by:
  1286.  
  1287.    a. Typing `:help' in Vi state
  1288.    b. Printing Viper manual, found in ./etc/viper.dvi
  1289.    c. Printing ViperCard, the Quick Reference, found in ./etc/viperCard.dvi
  1290.     
  1291. This startup message appears whenever you load Viper, unless you type `y' now."
  1292.               ))
  1293.             (goto-char (point-min))
  1294.             (if (y-or-n-p "Inhibit Viper startup message? ")
  1295.             (vip-save-setting
  1296.              'vip-inhibit-startup-message
  1297.              "Viper startup message inhibited"
  1298.              vip-custom-file-name t))
  1299.             ;;(kill-buffer (current-buffer))
  1300.             (message
  1301.              "The last message is in buffer `Viper Startup Message'")
  1302.             (sit-for 4)
  1303.             ))
  1304.           (vip-set-expert-level 'dont-change-unless)))
  1305.     (vip-change-state-to-vi))))
  1306.     
  1307. ;;;###autoload
  1308. (defalias 'vip-mode 'viper-mode)
  1309.  
  1310.  
  1311. ;; Switch from Insert state to Vi state.
  1312. (defun vip-exit-insert-state ()
  1313.   (interactive)
  1314.   (vip-change-state-to-vi))
  1315.  
  1316. (defun vip-set-mode-vars-for (state)
  1317.   "Sets Viper minor mode variables to put Viper's state STATE in effect."
  1318.   
  1319.   ;; Emacs state
  1320.   (setq vip-vi-minibuffer-minor-mode       nil
  1321.         vip-insert-minibuffer-minor-mode   nil
  1322.     vip-vi-intercept-minor-mode       nil
  1323.     vip-insert-intercept-minor-mode       nil
  1324.     
  1325.     vip-vi-local-user-minor-mode       nil
  1326.     vip-vi-kbd-minor-mode               nil
  1327.     vip-vi-global-user-minor-mode      nil
  1328.     vip-vi-state-modifier-minor-mode   nil
  1329.     vip-vi-diehard-minor-mode            nil
  1330.         vip-vi-basic-minor-mode              nil
  1331.     
  1332.     vip-replace-minor-mode                  nil
  1333.     
  1334.     vip-insert-local-user-minor-mode     nil
  1335.     vip-insert-kbd-minor-mode              nil
  1336.     vip-insert-global-user-minor-mode    nil
  1337.     vip-insert-state-modifier-minor-mode nil
  1338.     vip-insert-diehard-minor-mode          nil
  1339.     vip-insert-basic-minor-mode            nil
  1340.     vip-emacs-intercept-minor-mode       t
  1341.     vip-emacs-local-user-minor-mode      t
  1342.     vip-emacs-kbd-minor-mode             (not (vip-is-in-minibuffer))
  1343.     vip-emacs-global-user-minor-mode     t
  1344.     vip-emacs-state-modifier-minor-mode  t
  1345.     )
  1346.   
  1347.   ;; Vi state
  1348.   (if (eq state 'vi-state) ; adjust for vi-state
  1349.       (setq 
  1350.        vip-vi-intercept-minor-mode       t 
  1351.        vip-vi-minibuffer-minor-mode       (vip-is-in-minibuffer)
  1352.        vip-vi-local-user-minor-mode       t
  1353.        vip-vi-kbd-minor-mode               (not (vip-is-in-minibuffer))
  1354.        vip-vi-global-user-minor-mode       t
  1355.        vip-vi-state-modifier-minor-mode    t
  1356.        ;; don't let the diehard keymap block command completion 
  1357.        ;; and other things in the minibuffer
  1358.        vip-vi-diehard-minor-mode           (not
  1359.                         (or vip-want-emacs-keys-in-vi
  1360.                         (vip-is-in-minibuffer)))
  1361.        vip-vi-basic-minor-mode              t 
  1362.        vip-emacs-intercept-minor-mode       nil
  1363.        vip-emacs-local-user-minor-mode      nil
  1364.        vip-emacs-kbd-minor-mode             nil
  1365.        vip-emacs-global-user-minor-mode     nil
  1366.        vip-emacs-state-modifier-minor-mode  nil
  1367.        ))
  1368.   
  1369.   ;; Insert and Replace states
  1370.   (if (member state '(insert-state replace-state))
  1371.       (setq 
  1372.        vip-insert-intercept-minor-mode        t 
  1373.        vip-replace-minor-mode                 (eq state 'replace-state)
  1374.        vip-insert-minibuffer-minor-mode        (vip-is-in-minibuffer)
  1375.        vip-insert-local-user-minor-mode     t
  1376.        vip-insert-kbd-minor-mode             (not (vip-is-in-minibuffer))
  1377.        vip-insert-global-user-minor-mode    t
  1378.        vip-insert-state-modifier-minor-mode  t
  1379.        ;; don't let the diehard keymap block command completion 
  1380.        ;; and other things in the minibuffer
  1381.        vip-insert-diehard-minor-mode         (not
  1382.                          (or vip-want-emacs-keys-in-insert
  1383.                          (vip-is-in-minibuffer)))
  1384.        vip-insert-basic-minor-mode           t
  1385.        vip-emacs-intercept-minor-mode       nil
  1386.        vip-emacs-local-user-minor-mode      nil
  1387.        vip-emacs-kbd-minor-mode             nil
  1388.        vip-emacs-global-user-minor-mode     nil
  1389.        vip-emacs-state-modifier-minor-mode  nil
  1390.        ))
  1391.        
  1392.   ;; minibuffer faces
  1393.   (if (vip-has-face-support-p)
  1394.       (setq vip-minibuffer-current-face
  1395.         (cond ((eq state 'emacs-state) vip-minibuffer-emacs-face)
  1396.           ((eq state 'vi-state) vip-minibuffer-vi-face)
  1397.           ((memq state '(insert-state replace-state))
  1398.            vip-minibuffer-insert-face))))
  1399.   
  1400.   (if (vip-is-in-minibuffer)
  1401.       (vip-set-minibuffer-overlay))
  1402.   )
  1403.  
  1404. ;; This also takes care of the annoying incomplete lines in files.
  1405. ;; Also, this fixes `undo' to work vi-style for complex commands.
  1406. (defun vip-change-state-to-vi ()
  1407.   "Change Viper state to Vi."
  1408.   (interactive)
  1409.   (if (and vip-first-time (not (vip-is-in-minibuffer)))
  1410.       (viper-mode)
  1411.     (if overwrite-mode (overwrite-mode nil))
  1412.     (if abbrev-mode (expand-abbrev))
  1413.     (if (and auto-fill-function (> (current-column) fill-column))
  1414.     (funcall auto-fill-function))
  1415.     ;; don't leave whitespace lines around
  1416.     (if (and (memq last-command
  1417.            '(vip-autoindent
  1418.              vip-open-line vip-Open-line
  1419.              vip-replace-state-exit-cmd))
  1420.          (vip-over-whitespace-line))
  1421.     (indent-to-left-margin))
  1422.     (vip-add-newline-at-eob-if-necessary)
  1423.     (if vip-undo-needs-adjustment  (vip-adjust-undo))
  1424.     (vip-change-state 'vi-state)
  1425.  
  1426.     ;; always turn off iso-accents-mode, or else we won't be able to use the
  1427.     ;; keys `,',^ in Vi state, as they will do accents instead of Vi actions.
  1428.     (if (and (boundp 'iso-accents-mode) iso-accents-mode)
  1429.     (iso-accents-mode -1))
  1430.     
  1431.     ;; Protection against user errors in hooks
  1432.     (condition-case conds
  1433.     (run-hooks 'vip-vi-state-hook)
  1434.       (error
  1435.        (vip-message-conditions conds)))))
  1436.  
  1437. (defun vip-change-state-to-insert ()
  1438.   "Change Viper state to Insert."
  1439.   (interactive)
  1440.   (vip-change-state 'insert-state)
  1441.   (if (and vip-automatic-iso-accents (fboundp 'iso-accents-mode))
  1442.       (iso-accents-mode 1)) ; turn iso accents on
  1443.   
  1444.   ;; Protection against user errors in hooks
  1445.   (condition-case conds
  1446.       (run-hooks 'vip-insert-state-hook)
  1447.     (error
  1448.      (vip-message-conditions conds))))
  1449.      
  1450. (defsubst vip-downgrade-to-insert ()
  1451.  (setq vip-current-state 'insert-state
  1452.        vip-replace-minor-mode nil)
  1453.  )
  1454.  
  1455.     
  1456.   
  1457. ;; Change to replace state. When the end of replacement region is reached,
  1458. ;; replace state changes to insert state.
  1459. (defun vip-change-state-to-replace (&optional non-R-cmd)
  1460.   (vip-change-state 'replace-state)
  1461.   (if (and vip-automatic-iso-accents (fboundp 'iso-accents-mode))
  1462.       (iso-accents-mode 1)) ; turn iso accents on
  1463.   ;; Run insert-state-hook
  1464.   (condition-case conds
  1465.       (run-hooks 'vip-insert-state-hook 'vip-replace-state-hook)
  1466.     (error
  1467.      (vip-message-conditions conds)))
  1468.   
  1469.   (if non-R-cmd
  1470.       (vip-start-replace)
  1471.     ;; 'R' is implemented using Emacs's overwrite-mode
  1472.     (vip-start-R-mode))
  1473.   )
  1474.  
  1475.     
  1476. (defun vip-change-state-to-emacs ()
  1477.   "Change Viper state to Emacs."
  1478.   (interactive)
  1479.   (vip-change-state 'emacs-state)
  1480.   (if (and vip-automatic-iso-accents (fboundp 'iso-accents-mode))
  1481.       (iso-accents-mode 1)) ; turn iso accents on
  1482.   
  1483.   ;; Protection agains user errors in hooks
  1484.   (condition-case conds
  1485.       (run-hooks 'vip-emacs-state-hook)
  1486.     (error
  1487.      (vip-message-conditions conds))))
  1488.   
  1489. ;; escape to emacs mode termporarily
  1490. (defun vip-escape-to-emacs (arg &optional events)
  1491.   "Escape to Emacs state from Vi state for one Emacs command.
  1492. ARG is used as the prefix value for the executed command.  If
  1493. EVENTS is a list of events, which become the beginning of the command."
  1494.   (interactive "P")
  1495.   (vip-escape-to-state arg events 'emacs-state))
  1496.   
  1497. ;; escape to Vi mode termporarily
  1498. (defun vip-escape-to-vi ()
  1499.   "Escape from Emacs state to Vi state for one Vi 1-character command.
  1500. This doesn't work with prefix arguments or most complex commands like
  1501. cw, dw,  etc. But it does work with some 2-character commands,
  1502. like dd or dr."
  1503.   (interactive)
  1504.   (vip-escape-to-state nil nil 'vi-state))  
  1505.   
  1506. ;; Escape to STATE mode for one Emacs command.
  1507. (defun vip-escape-to-state (arg events state)
  1508.   (let (com key prefix-arg)
  1509.     ;; this temporarily turns off Viper's minor mode keymaps
  1510.     (vip-set-mode-vars-for state)
  1511.     (vip-normalize-minor-mode-map-alist)
  1512.     (if events (vip-set-unread-command-events events))
  1513.     
  1514.     ;; protect against keyboard quit and other errors
  1515.     (condition-case nil
  1516.     (progn
  1517.       (unwind-protect
  1518.           (progn
  1519.         (setq com (key-binding (setq key 
  1520.                          (if vip-xemacs-p
  1521.                          (read-key-sequence nil)
  1522.                            (read-key-sequence nil t)))))
  1523.         ;; In case of indirection--chase definitions.
  1524.         ;; Have to do it here because we execute this command under
  1525.         ;; different keymaps, so command-execute may not do the
  1526.         ;; right thing there
  1527.         (while (vectorp com) (setq com (key-binding com))))
  1528.         nil)
  1529.       ;; exec command in the right Viper state
  1530.       ;; otherwise, if we switch buffers in the escaped command,
  1531.       ;; Viper's mode vars will remain those of `state'. When we return
  1532.       ;; to the orig buffer, the bindings will be screwed up.
  1533.       (vip-set-mode-vars-for vip-current-state)
  1534.       
  1535.       ;; this-command, last-command-char, last-command-event
  1536.       (setq this-command com)
  1537.       (if vip-xemacs-p ; XEmacs represents key sequences as vectors
  1538.           (setq last-command-event (vip-seq-last-elt key)
  1539.             last-command-char (event-to-character last-command-event))
  1540.         ;; Emacs represents them as sequences (str or vec)
  1541.         (setq last-command-event (vip-seq-last-elt key)
  1542.           last-command-char last-command-event))
  1543.         
  1544.       (if (commandp com)
  1545.           (progn
  1546.         (setq prefix-arg arg)
  1547.         (command-execute com)))
  1548.       )
  1549.       (quit (ding))
  1550.       (error (beep 1))))
  1551.   (vip-set-mode-vars-for vip-current-state)) ; set state in new buffer
  1552.       
  1553. (defun vip-exec-form-in-emacs  (form)
  1554.   "Execute FORM in Emacs, temporarily disabling Viper's minor modes.
  1555. Similar to vip-escape-to-emacs, but accepts forms rather than keystrokes."
  1556.   (let ((buff (current-buffer))
  1557.     result)
  1558.     (vip-set-mode-vars-for 'emacs-state)
  1559.     (setq result (eval form))
  1560.     (if (not (equal buff (current-buffer))) ; cmd switched buffer
  1561.     (save-excursion
  1562.       (set-buffer buff)
  1563.       (vip-set-mode-vars-for vip-current-state)))
  1564.     (vip-set-mode-vars-for vip-current-state)
  1565.     result))
  1566.  
  1567.   
  1568. ;; This is needed because minor modes sometimes override essential Viper
  1569. ;; bindings. By letting Viper know which files these modes are in, it will
  1570. ;; arrange to reorganize minor-mode-map-alist so that things will work right.
  1571. (defun vip-harness-minor-mode (load-file)
  1572.   "Familiarize Viper with a minor mode defined in LOAD_FILE.
  1573. Minor modes that have their own keymaps may overshadow Viper keymaps.
  1574. This function is designed to make Viper aware of the packages that define
  1575. such minor modes.
  1576. Usage:
  1577.     (vip-harness-minor-mode load-file)
  1578.  
  1579. LOAD-FILE is a name of the file where the specific minor mode is defined.
  1580. Suffixes such as .el or .elc should be stripped."
  1581.  
  1582.   (interactive "sEnter name of the load file: ")
  1583.   
  1584.   (vip-eval-after-load load-file '(vip-normalize-minor-mode-map-alist))
  1585.   
  1586.   ;; Change the default for minor-mode-map-alist each time a harnessed minor
  1587.   ;; mode adds its own keymap to the a-list.
  1588.   (vip-eval-after-load
  1589.    load-file '(setq-default minor-mode-map-alist minor-mode-map-alist))
  1590.   )
  1591.  
  1592.  
  1593. (defun vip-ESC (arg)
  1594.   "Emulate ESC key in Emacs.
  1595. Prevents multiple escape keystrokes if vip-no-multiple-ESC is true. In that
  1596. case \@ will be bound to ESC. If vip-no-multiple-ESC is 'twice double ESC
  1597. would dings in vi-state. Other ESC sequences are emulated via the current
  1598. Emacs's major mode keymap. This is more convenient on dumb terminals and in
  1599. Emacs -nw, since this won't block functional keys such as up,down,
  1600. etc. Meta key also will work. When vip-no-multiple-ESC is nil, ESC key
  1601. behaves as in Emacs, any number of multiple escapes is allowed."
  1602.   (interactive "P")
  1603.   (let (char)
  1604.     (cond ((and (not vip-no-multiple-ESC) (eq vip-current-state 'vi-state))
  1605.        (setq char (vip-read-char-exclusive))
  1606.        (vip-escape-to-emacs arg (list ?\e char) ))
  1607.       ((and (eq vip-no-multiple-ESC 'twice) 
  1608.         (eq vip-current-state 'vi-state))
  1609.        (setq char (vip-read-char-exclusive))
  1610.        (if (= char (string-to-char vip-ESC-key))
  1611.            (ding)
  1612.          (vip-escape-to-emacs arg (list ?\e char) )))
  1613.       (t (ding)))
  1614.     ))
  1615.  
  1616. (defun vip-alternate-ESC (arg)
  1617.   "ESC key without checking for multiple keystrokes."
  1618.   (interactive "P")
  1619.   (vip-escape-to-emacs arg '(?\e)))
  1620.   
  1621.  
  1622. ;; Intercept ESC sequences on dumb terminals.
  1623. ;; Based on the idea contributed by Marcelino Veiga Tuimil <mveiga@dit.upm.es>
  1624.  
  1625. ;; Check if last key was ESC and if so try to reread it as a function key.
  1626. ;; But only if there are characters to read during a very short time.
  1627. ;; Returns the last event, if any.
  1628. (defun vip-envelop-ESC-key ()
  1629.   (let ((event last-input-event)
  1630.     (keyseq [nil])
  1631.     inhibit-quit)
  1632.     (if (vip-ESC-event-p event)
  1633.     (progn 
  1634.       (if (vip-fast-keysequence-p)
  1635.           (progn
  1636.         (let (minor-mode-map-alist)
  1637.           (vip-set-unread-command-events event)
  1638.           (setq keyseq
  1639.             (funcall
  1640.              (ad-get-orig-definition 'read-key-sequence) nil))
  1641.           ) ; let
  1642.         ;; If keyseq translates into something that still has ESC
  1643.         ;; at the beginning, separate ESC from the rest of the seq.
  1644.         ;; In XEmacs we check for events that are keypress meta-key
  1645.         ;; and convert them into [escape key]
  1646.         ;;
  1647.         ;; This is needed for the following reason:
  1648.         ;; If ESC is the first symbol, we interpret it as if the
  1649.         ;; user typed ESC and then quickly some other symbols.
  1650.         ;; If ESC is not the first one, then the key sequence
  1651.         ;; entered was apparently translated into a function key or
  1652.         ;; something (e.g., one may have
  1653.         ;; (define-key function-key-map "\e[192z" [f11])
  1654.         ;; which would translate the escape-sequence generated by
  1655.         ;; f11 in an xterm window into the symbolic key f11.
  1656.         ;;
  1657.         ;; If `first-key' is not an ESC event, we make it into the
  1658.         ;; last-command-event in order to pretend that this key was
  1659.         ;; pressed. This is needed to allow arrow keys to be bound to
  1660.         ;; macros. Otherwise, vip-exec-mapped-kbd-macro will think that
  1661.         ;; the last event was ESC and so it'll execute whatever is
  1662.         ;; bound to ESC. (Viper macros can't be bound to
  1663.         ;; ESC-sequences).
  1664.         (let* ((first-key (elt keyseq 0))
  1665.                (key-mod (event-modifiers first-key)))
  1666.           (cond ((vip-ESC-event-p first-key)
  1667.              ;; put keys following ESC on the unread list
  1668.              ;; and return ESC as the key-sequence
  1669.              (vip-set-unread-command-events (subseq keyseq 1))
  1670.              (setq last-input-event event
  1671.                    keyseq (if vip-emacs-p
  1672.                       "\e"
  1673.                     (vector (character-to-event ?\e)))))
  1674.             ((and vip-xemacs-p
  1675.                   (key-press-event-p first-key)
  1676.                   (equal '(meta) key-mod))
  1677.              (vip-set-unread-command-events 
  1678.               (vconcat (vector
  1679.                     (character-to-event (event-key first-key)))
  1680.                    (subseq keyseq 1)))
  1681.              (setq last-input-event event
  1682.                    keyseq (vector (character-to-event ?\e))))
  1683.             ((eventp first-key)
  1684.              (setq last-command-event first-key))
  1685.             ))
  1686.         ) ; end progn
  1687.         
  1688.         ;; this is escape event with nothing after it
  1689.         ;; put in unread-command-event and then re-read
  1690.         (vip-set-unread-command-events event)
  1691.         (setq keyseq
  1692.           (funcall (ad-get-orig-definition 'read-key-sequence) nil))
  1693.         ))
  1694.       ;; not an escape event
  1695.       (setq keyseq (vector event)))
  1696.     keyseq))
  1697.  
  1698.     
  1699.     
  1700. (defadvice read-key-sequence (around vip-read-keyseq-ad activate)
  1701.   "Harness to work for Viper. This advice is harmless---don't worry!"
  1702.   (let (inhibit-quit event keyseq)
  1703.     (setq keyseq ad-do-it)
  1704.     (setq event (if vip-xemacs-p
  1705.             (elt keyseq 0) ; XEmacs returns vector of events
  1706.           (elt (listify-key-sequence keyseq) 0)))
  1707.     (if (vip-ESC-event-p event)
  1708.     (let (unread-command-events)
  1709.       (vip-set-unread-command-events keyseq)
  1710.       (if (vip-fast-keysequence-p)
  1711.           (let ((vip-vi-global-user-minor-mode  nil)
  1712.             (vip-vi-local-user-minor-mode  nil)
  1713.             (vip-replace-minor-mode nil) ; actually unnecessary
  1714.             (vip-insert-global-user-minor-mode  nil)
  1715.             (vip-insert-local-user-minor-mode  nil))
  1716.         (setq keyseq ad-do-it)) 
  1717.         (setq keyseq ad-do-it))))
  1718.     keyseq))
  1719.     
  1720. (defadvice describe-key (before vip-read-keyseq-ad protect activate)
  1721.   "Force to read key via `read-key-sequence'."
  1722.   (interactive (list (vip-events-to-keys
  1723.               (read-key-sequence "Describe key: ")))))
  1724.  
  1725. (defadvice describe-key-briefly (before vip-read-keyseq-ad protect activate)
  1726.   "Force to read key via `read-key-sequence'."
  1727.   (interactive (list (vip-events-to-keys
  1728.               (read-key-sequence "Describe key briefly: ")))))
  1729.  
  1730. ;; Listen to ESC key.
  1731. ;; If a sequence of keys starting with ESC is issued with very short delays,
  1732. ;; interpret these keys in Emacs mode, so ESC won't be interpreted as a Vi key.
  1733. (defun vip-intercept-ESC-key ()
  1734.   "Function that implements ESC key in Viper emulation of Vi."
  1735.   (interactive)
  1736.   (let ((cmd (or (key-binding (vip-envelop-ESC-key)) 
  1737.          '(lambda () (interactive) (error "")))))
  1738.     
  1739.     ;; call the actual function to execute ESC (if no other symbols followed)
  1740.     ;; or the key bound to the ESC sequence (if the sequence was issued
  1741.     ;; with very short delay between characters.
  1742.     (if (eq cmd 'vip-intercept-ESC-key)
  1743.     (setq cmd
  1744.           (cond ((eq vip-current-state 'vi-state)
  1745.              'vip-ESC)
  1746.             ((eq vip-current-state 'insert-state)
  1747.              'vip-exit-insert-state) 
  1748.             ((eq vip-current-state 'replace-state)
  1749.              'vip-replace-state-exit-cmd)
  1750.             (t 'vip-change-state-to-vi)
  1751.             )))
  1752.     (call-interactively cmd)))
  1753.        
  1754.  
  1755.  
  1756. ;; prefix argument for Vi mode
  1757.  
  1758. ;; In Vi mode, prefix argument is a dotted pair (NUM . COM) where NUM
  1759. ;; represents the numeric value of the prefix argument and COM represents
  1760. ;; command prefix such as "c", "d", "m" and "y".
  1761.  
  1762. ;; Get value part of prefix-argument ARG.
  1763. (defsubst vip-p-val (arg)
  1764.   (cond ((null arg) 1)
  1765.     ((consp arg)
  1766.      (if (or (null (car arg)) (equal (car arg) '(nil)))
  1767.          1 (car arg)))
  1768.     (t arg)))
  1769.  
  1770. ;; Get raw value part of prefix-argument ARG.
  1771. (defsubst vip-P-val (arg)
  1772.   (cond ((consp arg) (car arg))
  1773.     (t arg)))
  1774.  
  1775. ;; Get com part of prefix-argument ARG.
  1776. (defsubst vip-getcom (arg)
  1777.   (cond ((null arg) nil)
  1778.     ((consp arg) (cdr arg))
  1779.     (t nil)))
  1780.  
  1781. ;; Get com part of prefix-argument ARG and modify it.
  1782. (defun vip-getCom (arg)
  1783.   (let ((com (vip-getcom arg)))
  1784.     (cond ((equal com ?c) ?C)
  1785.       ((equal com ?d) ?D)
  1786.       ((equal com ?y) ?Y)
  1787.       (t com))))
  1788.  
  1789.  
  1790. ;; Compute numeric prefix arg value. 
  1791. ;; Invoked by CHAR. COM is the command part obtained so far.
  1792. (defun vip-prefix-arg-value (event com)
  1793.   (let (value)
  1794.     ;; read while number
  1795.     (while (and (vip-characterp event) (>= event ?0) (<= event ?9))
  1796.       (setq value (+ (* (if (vip-characterp value) value 0) 10) (- event ?0)))
  1797.       (setq event (vip-read-event-convert-to-char)))
  1798.     
  1799.     (setq prefix-arg value)
  1800.     (if com (setq prefix-arg (cons prefix-arg com)))
  1801.     (while (eq event ?U)
  1802.       (vip-describe-arg prefix-arg)
  1803.       (setq event (vip-read-event-convert-to-char)))
  1804.     (vip-set-unread-command-events event)))
  1805.  
  1806. ;; Vi operator as prefix argument."
  1807. (defun vip-prefix-arg-com (char value com)
  1808.   (let ((cont t))
  1809.     (while (and cont
  1810.         (memq char
  1811.               (list ?c ?d ?y ?! ?< ?> ?= ?# ?r ?R ?\"
  1812.                 vip-buffer-search-char)))
  1813.       (if com
  1814.       ;; this means that we already have a command character, so we
  1815.       ;; construct a com list and exit while.  however, if char is "
  1816.       ;; it is an error.
  1817.       (progn
  1818.         ;; new com is (CHAR . OLDCOM)
  1819.         (if (memq char '(?# ?\")) (error ""))
  1820.         (setq com (cons char com))
  1821.         (setq cont nil))
  1822.     ;; If com is nil we set com as char, and read more.  Again, if char
  1823.     ;; is ", we read the name of register and store it in vip-use-register.
  1824.     ;; if char is !, =, or #, a complete com is formed so we exit the
  1825.     ;; while loop.
  1826.     (cond ((memq char '(?! ?=))
  1827.            (setq com char)
  1828.            (setq char (read-char))
  1829.            (setq cont nil))
  1830.           ((= char ?#)
  1831.            ;; read a char and encode it as com
  1832.            (setq com (+ 128 (read-char)))
  1833.            (setq char (read-char)))
  1834.           ((= char ?\")
  1835.            (let ((reg (read-char)))
  1836.          (if (vip-valid-register reg)
  1837.              (setq vip-use-register reg)
  1838.            (error ""))
  1839.          (setq char (read-char))))
  1840.           (t
  1841.            (setq com char)
  1842.            (setq char (vip-read-char-exclusive)))))))
  1843.   (if (atom com)
  1844.       ;; com is a single char, so we construct prefix-arg 
  1845.       ;; and if char is ?, describe prefix arg, otherwise exit by
  1846.       ;; pushing the char back into vip-set-unread-command-events
  1847.       ;; Since char is a command, the command will execute with the prefix
  1848.       ;; argument that we just constructed.
  1849.       (progn
  1850.     (setq prefix-arg (cons value com))
  1851.     (while (= char ?U)
  1852.       (vip-describe-arg prefix-arg)
  1853.       (setq char (read-char)))
  1854.     (vip-set-unread-command-events char)
  1855.     )
  1856.     ;; as com is non-nil, this means that we have a command to execute
  1857.     (if (memq (car com) '(?r ?R))
  1858.     ;; execute apropriate region command.
  1859.     (let ((char (car com)) (com (cdr com)))
  1860.       (setq prefix-arg (cons value com))
  1861.       (if (= char ?r) (vip-region prefix-arg)
  1862.         (vip-Region prefix-arg))
  1863.       ;; reset prefix-arg
  1864.       (setq prefix-arg nil))
  1865.       ;; otherwise, reset prefix arg and call appropriate command
  1866.       (setq value (if (null value) 1 value))
  1867.       (setq prefix-arg nil)
  1868.       (cond ((equal com '(?c . ?c)) (vip-line (cons value ?C)))
  1869.         ((equal com '(?d . ?d)) (vip-line (cons value ?D)))
  1870.         ((equal com '(?d . ?y)) (vip-yank-defun))
  1871.         ((equal com '(?y . ?y)) (vip-line (cons value ?Y)))
  1872.         ((equal com '(?< . ?<)) (vip-line (cons value ?<)))
  1873.         ((equal com '(?> . ?>)) (vip-line (cons value ?>)))
  1874.         ((equal com '(?! . ?!)) (vip-line (cons value ?!)))
  1875.         ((equal com '(?= . ?=)) (vip-line (cons value ?=)))
  1876.         (t (error ""))))))
  1877.  
  1878. (defun vip-describe-arg (arg)
  1879.   (let (val com)
  1880.     (setq val (vip-P-val arg)
  1881.       com (vip-getcom arg))
  1882.     (if (null val)
  1883.     (if (null com)
  1884.         (message "Value is nil, and command is nil")
  1885.       (message "Value is nil, and command is `%c'" com))
  1886.       (if (null com)
  1887.       (message "Value is `%d', and command is nil" val)
  1888.     (message "Value is `%d', and command is `%c'" val com)))))
  1889.  
  1890. (defun vip-digit-argument (arg)
  1891.   "Begin numeric argument for the next command."
  1892.   (interactive "P")
  1893.   (vip-leave-region-active)
  1894.   (vip-prefix-arg-value last-command-char
  1895.             (if (consp arg) (cdr arg) nil)))
  1896.  
  1897. (defun vip-command-argument (arg)
  1898.   "Accept a motion command as an argument."
  1899.   (interactive "P")
  1900.   (condition-case nil
  1901.       (vip-prefix-arg-com
  1902.        last-command-char   
  1903.        (cond ((null arg) nil)
  1904.          ((consp arg) (car arg))
  1905.          ((integerp arg) arg)
  1906.          (t (error vip-InvalidCommandArgument)))
  1907.        (cond ((null arg) nil)
  1908.          ((consp arg) (cdr arg))
  1909.          ((integerp arg) nil)
  1910.          (t (error vip-InvalidCommandArgument))))
  1911.     (quit (setq vip-use-register nil)
  1912.       (signal 'quit nil)))
  1913.   (vip-deactivate-mark))
  1914.  
  1915.  
  1916. ;; repeat last destructive command
  1917.  
  1918. ;; Append region to text in register REG.
  1919. ;; START and END are buffer positions indicating what to append.
  1920. (defsubst vip-append-to-register (reg start end)
  1921.   (set-register reg (concat (if (stringp (get-register reg))
  1922.                 (get-register reg) "")
  1923.                 (buffer-substring start end))))
  1924.  
  1925. ;; Saves last inserted text for possible use by vip-repeat command.
  1926. (defun vip-save-last-insertion (beg end)
  1927.   (setq vip-last-insertion (buffer-substring beg end))
  1928.   (or (< (length vip-d-com) 5)
  1929.       (setcar (nthcdr 4 vip-d-com) vip-last-insertion))
  1930.   (or (null vip-command-ring)
  1931.       (ring-empty-p vip-command-ring)
  1932.       (progn
  1933.     (setcar (nthcdr 4 (vip-current-ring-item vip-command-ring))
  1934.         vip-last-insertion)
  1935.     ;; del most recent elt, if identical to the second most-recent
  1936.     (vip-cleanup-ring vip-command-ring)))
  1937.   )
  1938.     
  1939. (defsubst vip-yank-last-insertion ()
  1940.   "Inserts the text saved by the previous vip-save-last-insertion command."
  1941.   (condition-case nil
  1942.       (insert vip-last-insertion)
  1943.     (error nil)))
  1944.   
  1945.                 
  1946. ;; define functions to be executed
  1947.  
  1948. ;; invoked by the `C' command
  1949. (defun vip-exec-change (m-com com) 
  1950.   ;; handle C cmd at the eol and at eob.
  1951.   (if (or (and (eolp) (= vip-com-point (point)))
  1952.       (= vip-com-point (point-max)))
  1953.       (progn
  1954.     (insert " ")(backward-char 1)))
  1955.   (if (= vip-com-point (point))
  1956.       (vip-forward-char-carefully))
  1957.   (if (= com ?c)
  1958.       (vip-change vip-com-point (point))
  1959.     (vip-change-subr vip-com-point (point))))
  1960.  
  1961. ;; this is invoked by vip-substitute-line
  1962. (defun vip-exec-Change (m-com com)
  1963.   (save-excursion
  1964.     (set-mark vip-com-point)
  1965.     (vip-enlarge-region (mark t) (point))
  1966.     (if vip-use-register
  1967.     (progn
  1968.       (cond ((vip-valid-register vip-use-register '(letter digit))
  1969.          ;;(vip-valid-register vip-use-register '(letter)
  1970.          (copy-to-register
  1971.           vip-use-register (mark t) (point) nil))
  1972.         ((vip-valid-register vip-use-register '(Letter))
  1973.          (vip-append-to-register
  1974.           (downcase vip-use-register) (mark t) (point)))
  1975.         (t (setq vip-use-register nil)
  1976.            (error vip-InvalidRegister vip-use-register)))
  1977.       (setq vip-use-register nil)))
  1978.     (delete-region (mark t) (point)))
  1979.   (open-line 1)
  1980.   (if (= com ?C) (vip-change-mode-to-insert) (vip-yank-last-insertion)))
  1981.  
  1982. (defun vip-exec-delete (m-com com)
  1983.   (if vip-use-register
  1984.       (progn
  1985.     (cond ((vip-valid-register vip-use-register '(letter digit))
  1986.            ;;(vip-valid-register vip-use-register '(letter))
  1987.            (copy-to-register
  1988.         vip-use-register vip-com-point (point) nil))
  1989.           ((vip-valid-register vip-use-register '(Letter))
  1990.            (vip-append-to-register
  1991.         (downcase vip-use-register) vip-com-point (point)))
  1992.           (t (setq vip-use-register nil)
  1993.          (error vip-InvalidRegister vip-use-register)))
  1994.     (setq vip-use-register nil)))
  1995.   (setq last-command
  1996.     (if (eq last-command 'd-command) 'kill-region nil))
  1997.   (kill-region vip-com-point (point))
  1998.   (setq this-command 'd-command)
  1999.   (if vip-ex-style-motion
  2000.       (if (and (eolp) (not (bolp))) (backward-char 1))))
  2001.  
  2002. (defun vip-exec-Delete (m-com com)
  2003.   (save-excursion
  2004.     (set-mark vip-com-point)
  2005.     (vip-enlarge-region (mark t) (point))
  2006.     (if vip-use-register
  2007.     (progn
  2008.       (cond ((vip-valid-register vip-use-register '(letter digit))
  2009.          ;;(vip-valid-register vip-use-register '(letter))
  2010.          (copy-to-register
  2011.           vip-use-register (mark t) (point) nil))
  2012.         ((vip-valid-register vip-use-register '(Letter))
  2013.          (vip-append-to-register
  2014.           (downcase vip-use-register) (mark t) (point)))
  2015.         (t (setq vip-use-register nil)
  2016.            (error vip-InvalidRegister vip-use-register)))
  2017.       (setq vip-use-register nil)))
  2018.     (setq last-command
  2019.       (if (eq last-command 'D-command) 'kill-region nil))
  2020.     (kill-region (mark t) (point))
  2021.     (if (eq m-com 'vip-line) (setq this-command 'D-command)))
  2022.   (back-to-indentation))
  2023.  
  2024. (defun vip-exec-yank (m-com com)
  2025.   (if vip-use-register
  2026.       (progn
  2027.     (cond ((vip-valid-register vip-use-register '(letter digit))
  2028.            ;; (vip-valid-register vip-use-register '(letter))
  2029.            (copy-to-register
  2030.         vip-use-register vip-com-point (point) nil))
  2031.           ((vip-valid-register vip-use-register '(Letter))
  2032.            (vip-append-to-register
  2033.         (downcase vip-use-register) vip-com-point (point)))
  2034.           (t (setq vip-use-register nil)
  2035.          (error vip-InvalidRegister vip-use-register)))
  2036.     (setq vip-use-register nil)))
  2037.   (setq last-command nil)
  2038.   (copy-region-as-kill vip-com-point (point))
  2039.   (goto-char vip-com-point))
  2040.  
  2041. (defun vip-exec-Yank (m-com com)
  2042.   (save-excursion
  2043.     (set-mark vip-com-point)
  2044.     (vip-enlarge-region (mark t) (point))
  2045.     (if vip-use-register
  2046.     (progn
  2047.       (cond ((vip-valid-register vip-use-register '(letter digit))
  2048.          (copy-to-register
  2049.           vip-use-register (mark t) (point) nil))
  2050.         ((vip-valid-register vip-use-register '(Letter))
  2051.          (vip-append-to-register
  2052.           (downcase vip-use-register) (mark t) (point)))
  2053.         (t (setq vip-use-register nil)
  2054.            (error vip-InvalidRegister  vip-use-register)))
  2055.       (setq vip-use-register nil)))
  2056.     (setq last-command nil)
  2057.     (copy-region-as-kill (mark t) (point)))
  2058.   (vip-deactivate-mark)
  2059.   (goto-char vip-com-point))
  2060.  
  2061. (defun vip-exec-bang (m-com com)
  2062.   (save-excursion
  2063.     (set-mark vip-com-point)
  2064.     (vip-enlarge-region (mark t) (point))
  2065.     (shell-command-on-region
  2066.      (mark t) (point)
  2067.      (if (= com ?!)
  2068.      (setq vip-last-shell-com
  2069.            (vip-read-string-with-history 
  2070.         "!"
  2071.         nil
  2072.         'vip-shell-history
  2073.         (car vip-shell-history)
  2074.         ))
  2075.        vip-last-shell-com)
  2076.      t)))
  2077.  
  2078. (defun vip-exec-equals (m-com com)
  2079.   (save-excursion
  2080.     (set-mark vip-com-point)
  2081.     (vip-enlarge-region (mark t) (point))
  2082.     (if (> (mark t) (point)) (exchange-point-and-mark))
  2083.     (indent-region (mark t) (point) nil)))
  2084.  
  2085. (defun vip-exec-shift (m-com com)
  2086.   (save-excursion
  2087.     (set-mark vip-com-point)
  2088.     (vip-enlarge-region (mark t) (point))
  2089.     (if (> (mark t) (point)) (exchange-point-and-mark))
  2090.     (indent-rigidly (mark t) (point) 
  2091.             (if (= com ?>)
  2092.             vip-shift-width
  2093.               (- vip-shift-width))))
  2094.   ;; return point to where it was before shift
  2095.   (goto-char vip-com-point))
  2096.  
  2097. ;; this is needed because some commands fake com by setting it to ?r, which
  2098. ;; denotes repeated insert command.
  2099. (defsubst vip-exec-dummy (m-com com)
  2100.   nil)
  2101.  
  2102. (defun vip-exec-buffer-search (m-com com)
  2103.   (setq vip-s-string (buffer-substring (point) vip-com-point))
  2104.   (setq vip-s-forward t)
  2105.   (setq vip-search-history (cons vip-s-string vip-search-history))
  2106.   (vip-search vip-s-string vip-s-forward 1))
  2107.  
  2108. (defvar vip-exec-array (make-vector 128 nil))
  2109.  
  2110. ;; Using a dispatch array allows adding functions like buffer search
  2111. ;; without affecting other functions. Buffer search can now be bound
  2112. ;; to any character.
  2113.  
  2114. (aset vip-exec-array ?c 'vip-exec-change)
  2115. (aset vip-exec-array ?C 'vip-exec-Change)
  2116. (aset vip-exec-array ?d 'vip-exec-delete)
  2117. (aset vip-exec-array ?D 'vip-exec-Delete)
  2118. (aset vip-exec-array ?y 'vip-exec-yank)
  2119. (aset vip-exec-array ?Y 'vip-exec-Yank)
  2120. (aset vip-exec-array ?r 'vip-exec-dummy)
  2121. (aset vip-exec-array ?! 'vip-exec-bang)
  2122. (aset vip-exec-array ?< 'vip-exec-shift)
  2123. (aset vip-exec-array ?> 'vip-exec-shift)
  2124. (aset vip-exec-array ?= 'vip-exec-equals)
  2125.  
  2126.  
  2127.  
  2128. ;; This function is called by various movement commands to execute a
  2129. ;; destructive command on the region specified by the movement command. For
  2130. ;; instance, if the user types cw, then the command vip-forward-word will
  2131. ;; call vip-execute-com to execute vip-exec-change, which eventually will
  2132. ;; call vip-change to invoke the replace mode on the region.
  2133. ;;
  2134. ;; The list (M-COM VAL COM REG INSETED-TEXT COMMAND-KEYS) is set to
  2135. ;; vip-d-com for later use by vip-repeat.
  2136. (defun vip-execute-com (m-com val com)
  2137.   (let ((reg vip-use-register))
  2138.     ;; this is the special command `#'
  2139.     (if (> com 128)
  2140.     (vip-special-prefix-com (- com 128))
  2141.       (let ((fn (aref vip-exec-array (if (< com 0) (- com) com))))
  2142.     (if (null fn)
  2143.         (error "%c: %s" com vip-InvalidViCommand)
  2144.       (funcall fn m-com com))))
  2145.     (if (vip-dotable-command-p com)
  2146.     (vip-set-destructive-command
  2147.      (list m-com val
  2148.            (if (memq com (list ?c ?C ?!)) (- com) com)
  2149.            reg nil nil)))
  2150.     ))
  2151.  
  2152.  
  2153. (defun vip-repeat (arg)
  2154.   "Re-execute last destructive command.
  2155. Use the info in vip-d-com, which has the form
  2156. \(com val ch reg inserted-text command-keys\),
  2157. where `com' is the command to be re-executed, `val' is the
  2158. argument to `com', `ch' is a flag for repeat, and `reg' is optional;
  2159. if it exists, it is the name of the register for `com'.
  2160. If the prefix argument, ARG, is non-nil, it is used instead of `val'."
  2161.   (interactive "P")
  2162.   (let ((save-point (point)) ; save point before repeating prev cmd
  2163.     ;; Pass along that we are repeating a destructive command
  2164.     ;; This tells vip-set-destructive-command not to update
  2165.     ;; vip-command-ring
  2166.     (vip-intermediate-command 'vip-repeat))
  2167.     (if (eq last-command 'vip-undo)
  2168.     ;; if the last command was vip-undo, then undo-more
  2169.     (vip-undo-more)
  2170.       ;; otherwise execute the command stored in vip-d-com.  if arg is non-nil
  2171.       ;; its prefix value is used as new prefix value for the command.
  2172.       (let ((m-com (car vip-d-com))
  2173.         (val (vip-P-val arg))
  2174.         (com (nth 2 vip-d-com))
  2175.         (reg (nth 3 vip-d-com)))
  2176.         (if (null val) (setq val (nth 1 vip-d-com)))
  2177.         (if (null m-com) (error "No previous command to repeat."))
  2178.         (setq vip-use-register reg)
  2179.     (if (nth 4 vip-d-com) ; text inserted by command
  2180.         (setq vip-last-insertion (nth 4 vip-d-com)
  2181.           vip-d-char (nth 4 vip-d-com)))
  2182.         (funcall m-com (cons val com))
  2183.         (if (and vip-keep-point-on-repeat (< save-point (point)))
  2184.         (goto-char save-point)) ; go back to before repeat.
  2185.     (if (and (eolp) (not (bolp)))
  2186.         (backward-char 1))
  2187.      ))
  2188.   (if vip-undo-needs-adjustment (vip-adjust-undo)) ; take care of undo
  2189.   ;; If the prev cmd was rotating the command ring, this means that `.' has
  2190.   ;; just executed a command from that ring. So, push it on the ring again.
  2191.   ;; If we are just executing previous command , then don't push vip-d-com
  2192.   ;; because vip-d-com is not fully constructed in this case (its keys and
  2193.   ;; the inserted text may be nil). Besides, in this case, the command
  2194.   ;; executed by `.' is already on the ring.
  2195.   (if (eq last-command 'vip-display-current-destructive-command)
  2196.       (vip-push-onto-ring vip-d-com 'vip-command-ring))
  2197.   (vip-deactivate-mark)
  2198.   ))
  2199.   
  2200. (defun vip-repeat-from-history ()
  2201.   "Repeat a destructive command from history.
  2202. Doesn't change vip-command-ring in any way, so `.' will work as before
  2203. executing this command.
  2204. This command is supposed to be bound to a two-character Vi macro where
  2205. the second character is a digit 0 to 9. The digit indicates which
  2206. history command to execute. `<char>0' is equivalent to `.', `<char>1'
  2207. invokes the command before that, etc."
  2208.   (interactive)
  2209.   (let* ((vip-intermediate-command 'repeating-display-destructive-command)
  2210.      (idx (cond (vip-this-kbd-macro
  2211.               (string-to-number
  2212.                (symbol-name (elt vip-this-kbd-macro 1))))
  2213.             (t 0)))
  2214.      (num idx)
  2215.      (vip-d-com vip-d-com))
  2216.  
  2217.     (or (and (numberp num) (<= 0 num) (<= num 9))
  2218.     (progn
  2219.       (setq idx 0
  2220.         num 0)
  2221.       (message
  2222.        "`vip-repeat-from-history' must be invoked as a Vi macro bound to `<key><digit>'")))
  2223.     (while (< 0 num)
  2224.       (setq vip-d-com (vip-special-ring-rotate1 vip-command-ring -1))
  2225.       (setq num (1- num)))
  2226.     (vip-repeat nil)
  2227.     (while (> idx num)
  2228.       (vip-special-ring-rotate1 vip-command-ring 1)
  2229.       (setq num (1+ num)))
  2230.     ))
  2231.       
  2232.  
  2233. ;; This command is invoked interactively by the key sequence #<char>
  2234. (defun vip-special-prefix-com (char)
  2235.   (cond ((= char ?c)
  2236.      (downcase-region (min vip-com-point (point))
  2237.               (max vip-com-point (point))))
  2238.     ((= char ?C)
  2239.      (upcase-region (min vip-com-point (point))
  2240.             (max vip-com-point (point))))
  2241.     ((= char ?g)
  2242.      (push-mark vip-com-point t)
  2243.      (vip-global-execute))
  2244.     ((= char ?q)
  2245.      (push-mark vip-com-point t)
  2246.      (vip-quote-region))
  2247.     ((= char ?s) (funcall vip-spell-function vip-com-point (point)))
  2248.     (t (error "#%c: %s" char vip-InvalidViCommand))))
  2249.  
  2250.  
  2251. ;; undoing
  2252.  
  2253. (defun vip-undo ()
  2254.   "Undo previous change."
  2255.   (interactive)
  2256.   (message "undo!")
  2257.   (let ((modified (buffer-modified-p))
  2258.         (before-undo-pt (point-marker))
  2259.     (after-change-functions after-change-functions)
  2260.     undo-beg-posn undo-end-posn)
  2261.     
  2262.     ;; no need to remove this hook, since this var has scope inside a let.
  2263.     (add-hook 'after-change-functions
  2264.           '(lambda (beg end len)
  2265.          (setq undo-beg-posn beg
  2266.                undo-end-posn (or end beg))))
  2267.   
  2268.     (undo-start)
  2269.     (undo-more 2)
  2270.     (setq undo-beg-posn (or undo-beg-posn before-undo-pt)
  2271.       undo-end-posn (or undo-end-posn undo-beg-posn))
  2272.     
  2273.     (goto-char undo-beg-posn)
  2274.     (sit-for 0)
  2275.     (if (and vip-keep-point-on-undo
  2276.          (pos-visible-in-window-p before-undo-pt))
  2277.     (progn
  2278.       (push-mark (point-marker) t) 
  2279.       (vip-sit-for-short 300)
  2280.       (goto-char undo-end-posn)
  2281.       (vip-sit-for-short 300)
  2282.       (if (and (> (abs (- undo-beg-posn before-undo-pt)) 1)
  2283.           (> (abs (- undo-end-posn before-undo-pt)) 1))
  2284.           (goto-char before-undo-pt)
  2285.         (goto-char undo-beg-posn)))
  2286.       (push-mark before-undo-pt t))
  2287.     (if (and (eolp) (not (bolp))) (backward-char 1))
  2288.     (if (not modified) (set-buffer-modified-p t)))
  2289.   (setq this-command 'vip-undo))
  2290.  
  2291. ;; Continue undoing previous changes.
  2292. (defun vip-undo-more ()
  2293.   (message "undo more!")
  2294.   (condition-case nil
  2295.       (undo-more 1)
  2296.     (error (beep)
  2297.        (message "No further undo information in this buffer")))
  2298.   (if (and (eolp) (not (bolp))) (backward-char 1))
  2299.   (setq this-command 'vip-undo))
  2300.  
  2301. ;; The following two functions are used to set up undo properly.
  2302. ;; In VI, unlike Emacs, if you open a line, say, and add a bunch of lines,
  2303. ;; they are undone all at once.  
  2304. (defun vip-adjust-undo ()
  2305.   (let ((inhibit-quit t)
  2306.     tmp tmp2)
  2307.     (setq vip-undo-needs-adjustment nil)
  2308.     (if (listp buffer-undo-list)
  2309.     (if (setq tmp (memq vip-buffer-undo-list-mark buffer-undo-list))
  2310.         (progn
  2311.           (setq tmp2 (cdr tmp)) ; the part after mark
  2312.           
  2313.           ;; cut tail from buffer-undo-list temporarily by direct
  2314.           ;; manipulation with pointers in buffer-undo-list
  2315.           (setcdr tmp nil)
  2316.           
  2317.           (setq buffer-undo-list (delq nil buffer-undo-list))
  2318.           (setq buffer-undo-list
  2319.             (delq vip-buffer-undo-list-mark buffer-undo-list))
  2320.           ;; restore tail of buffer-undo-list
  2321.           (setq buffer-undo-list (nconc buffer-undo-list tmp2)))
  2322.       (setq buffer-undo-list (delq nil buffer-undo-list))))))
  2323.   
  2324.  
  2325. (defun vip-set-complex-command-for-undo ()  
  2326.   (if (listp buffer-undo-list)
  2327.       (if (not vip-undo-needs-adjustment)
  2328.       (let ((inhibit-quit t))
  2329.         (setq buffer-undo-list 
  2330.           (cons vip-buffer-undo-list-mark buffer-undo-list))
  2331.         (setq vip-undo-needs-adjustment t)))))
  2332.  
  2333.  
  2334.  
  2335.       
  2336. (defun vip-display-current-destructive-command ()
  2337.   (let ((text (nth 4 vip-d-com))
  2338.     (keys (nth 5 vip-d-com))
  2339.     (max-text-len 30))
  2340.     
  2341.     (setq this-command 'vip-display-current-destructive-command)
  2342.     
  2343.     (message " `.' runs  %s%s"
  2344.          (concat "`" (vip-array-to-string keys) "'")
  2345.          (vip-abbreviate-string text max-text-len
  2346.                     "  inserting  `" "'" "    ......."))
  2347.     ))
  2348.     
  2349.     
  2350. ;; don't change vip-d-com if it was vip-repeat command invoked with `.'
  2351. ;; or in some other way (non-interactively).
  2352. (defun vip-set-destructive-command (list)
  2353.   (or (eq vip-intermediate-command 'vip-repeat)
  2354.       (progn
  2355.     (setq vip-d-com list)
  2356.     (setcar (nthcdr 5 vip-d-com)
  2357.         (vip-array-to-string (this-command-keys)))
  2358.     (vip-push-onto-ring vip-d-com 'vip-command-ring))))
  2359.     
  2360. (defun vip-prev-destructive-command (next)
  2361.   "Find previous destructive command in the history of destructive commands.
  2362. With prefix argument, find next destructive command."
  2363.   (interactive "P")
  2364.   (let (cmd vip-intermediate-command)
  2365.     (if (eq last-command 'vip-display-current-destructive-command)
  2366.     ;; repeated search through command history
  2367.     (setq vip-intermediate-command 'repeating-display-destructive-command)
  2368.       ;; first search through command history--set temp ring
  2369.       (setq vip-temp-command-ring (copy-list vip-command-ring))) 
  2370.     (setq cmd (if next
  2371.           (vip-special-ring-rotate1 vip-temp-command-ring 1)
  2372.         (vip-special-ring-rotate1 vip-temp-command-ring -1)))
  2373.     (if (null cmd)
  2374.     ()
  2375.       (setq vip-d-com cmd))
  2376.     (vip-display-current-destructive-command)))
  2377.       
  2378. (defun vip-next-destructive-command ()
  2379.   "Find next destructive command in the history of destructive commands."
  2380.   (interactive)
  2381.   (vip-prev-destructive-command 'next))
  2382.   
  2383. (defun vip-insert-prev-from-insertion-ring (arg)
  2384.   "Cycle through insertion ring in the direction of older insertions.
  2385. Undoes previous insertion and inserts new.
  2386. With prefix argument, cycles in the direction of newer elements.
  2387. In minibuffer, this command executes whatever the invocation key is bound
  2388. to in the global map, instead of cycling through the insertion ring."
  2389.   (interactive "P")
  2390.   (let (vip-intermediate-command)
  2391.     (if (eq last-command 'vip-insert-from-insertion-ring)
  2392.     (progn  ; repeated search through insertion history
  2393.       (setq vip-intermediate-command 'repeating-insertion-from-ring)
  2394.       (if (eq vip-current-state 'replace-state)
  2395.           (undo 1)
  2396.         (if vip-last-inserted-string-from-insertion-ring
  2397.         (backward-delete-char
  2398.          (length vip-last-inserted-string-from-insertion-ring))))
  2399.       )
  2400.       ;;first search through insertion history
  2401.       (setq vip-temp-insertion-ring (copy-list vip-insertion-ring)))
  2402.     (setq this-command 'vip-insert-from-insertion-ring)
  2403.     ;; so that things will be undone properly
  2404.     (setq buffer-undo-list (cons nil buffer-undo-list))
  2405.     (setq vip-last-inserted-string-from-insertion-ring
  2406.       (vip-special-ring-rotate1 vip-temp-insertion-ring (if arg 1 -1)))
  2407.     
  2408.     ;; this change of vip-intermediate-command must come after
  2409.     ;; vip-special-ring-rotate1, so that the ring will rotate, but before the
  2410.     ;; insertion.
  2411.     (setq vip-intermediate-command nil)
  2412.     (if vip-last-inserted-string-from-insertion-ring
  2413.     (insert vip-last-inserted-string-from-insertion-ring))
  2414.     ))
  2415.  
  2416. (defun vip-insert-next-from-insertion-ring ()
  2417.   "Cycle through insertion ring in the direction of older insertions.
  2418. Undo previous insertion and inserts new."
  2419.   (interactive)
  2420.   (vip-insert-prev-from-insertion-ring 'next))
  2421.     
  2422.  
  2423. ;; some region utilities
  2424.  
  2425. ;; If at the last line of buffer, add \\n before eob, if newline is missing.
  2426. (defun vip-add-newline-at-eob-if-necessary ()
  2427.   (save-excursion
  2428.       (end-of-line)
  2429.       ;; make sure all lines end with newline, unless in the minibuffer or
  2430.       ;; when requested otherwise (require-final-newline is nil)
  2431.       (if (and (eobp)
  2432.            (not (bolp))
  2433.            require-final-newline
  2434.            (not (vip-is-in-minibuffer))
  2435.            (not buffer-read-only))
  2436.       (insert "\n"))))
  2437.  
  2438. (defun vip-yank-defun ()
  2439.   (mark-defun)
  2440.   (copy-region-as-kill (point) (mark t)))
  2441.  
  2442. ;; Enlarge region between BEG and END.
  2443. (defun vip-enlarge-region (beg end)
  2444.   (or beg (setq beg end)) ; if beg is nil, set to end
  2445.   (or end (setq end beg)) ; if end is nil, set to beg
  2446.   
  2447.   (if (< beg end)
  2448.       (progn (goto-char beg) (set-mark end))
  2449.     (goto-char end)
  2450.     (set-mark beg))
  2451.   (beginning-of-line)
  2452.   (exchange-point-and-mark)
  2453.   (if (or (not (eobp)) (not (bolp))) (forward-line 1))
  2454.   (if (not (eobp)) (beginning-of-line))
  2455.   (if (> beg end) (exchange-point-and-mark)))
  2456.  
  2457.  
  2458. ;; Quote region by each line with a user supplied string.
  2459. (defun vip-quote-region ()
  2460.   (setq vip-quote-string
  2461.     (vip-read-string-with-history
  2462.      "Quote string: "
  2463.      nil
  2464.      'vip-quote-region-history
  2465.      vip-quote-string))
  2466.   (vip-enlarge-region (point) (mark t))
  2467.   (if (> (point) (mark t)) (exchange-point-and-mark))
  2468.   (insert vip-quote-string)
  2469.   (beginning-of-line)
  2470.   (forward-line 1)
  2471.   (while (and (< (point) (mark t)) (bolp))
  2472.     (insert vip-quote-string)
  2473.     (beginning-of-line)
  2474.     (forward-line 1)))
  2475.  
  2476. ;;  Tells whether BEG is on the same line as END.
  2477. ;;  If one of the args is nil, it'll return nil.
  2478. (defun vip-same-line (beg end)
  2479.    (let ((selective-display nil))
  2480.      (cond ((and beg end)
  2481.         ;; This 'if' is needed because Emacs treats the next empty line
  2482.         ;; as part of the previous line.
  2483.         (if (or (> beg (point-max)) (> end (point-max))) ; out of range
  2484.         ()
  2485.           (if (and (> end beg) (= (vip-line-pos 'start) end))
  2486.           (setq end (min (1+ end) (point-max))))
  2487.           (if (and (> beg end) (= (vip-line-pos 'start) beg))
  2488.           (setq beg (min (1+ beg) (point-max))))
  2489.           (<= (count-lines beg end) 1) ))
  2490.        
  2491.        (t nil))
  2492.      ))
  2493.      
  2494.      
  2495. ;; Check if the string ends with a newline.
  2496. (defun vip-end-with-a-newline-p (string)
  2497.   (or (string= string "")
  2498.       (= (vip-seq-last-elt string) ?\n)))
  2499.  
  2500. (defun vip-tmp-insert-at-eob (msg)
  2501.   (let ((savemax (point-max)))
  2502.       (goto-char savemax)
  2503.       (insert msg)
  2504.       (sit-for 2)
  2505.       (goto-char savemax) (delete-region (point) (point-max))
  2506.       ))  
  2507.       
  2508.  
  2509.  
  2510. ;;; Minibuffer business
  2511.         
  2512. (defsubst vip-set-minibuffer-style ()
  2513.   (add-hook 'minibuffer-setup-hook 'vip-minibuffer-setup-sentinel))
  2514.   
  2515.   
  2516. (defun vip-minibuffer-setup-sentinel ()
  2517.   (let ((hook (if vip-vi-style-in-minibuffer
  2518.           'vip-change-state-to-insert
  2519.         'vip-change-state-to-emacs)))
  2520.     (funcall hook)
  2521.     ))
  2522.   
  2523. ;; Interpret last event in the local map
  2524. (defun vip-exit-minibuffer ()
  2525.   (interactive)
  2526.   (let (command)
  2527.     (setq command (local-key-binding (char-to-string last-command-char)))
  2528.     (if command
  2529.     (command-execute command)
  2530.       (exit-minibuffer))))
  2531.   
  2532.  
  2533. (defun vip-set-search-face ()
  2534.   (if (vip-has-face-support-p)
  2535.       (defvar vip-search-face
  2536.     (progn
  2537.       (make-face 'vip-search-face)
  2538.       (vip-hide-face 'vip-search-face)
  2539.       (or (face-differs-from-default-p 'vip-search-face)
  2540.           ;; face wasn't set in .vip or .Xdefaults
  2541.           (if (vip-can-use-colors "Black" "khaki")
  2542.           (progn
  2543.             (set-face-background 'vip-search-face "khaki")
  2544.             (set-face-foreground 'vip-search-face "Black"))
  2545.         (copy-face 'italic 'vip-search-face)
  2546.         (set-face-underline-p 'vip-search-face t)))
  2547.       'vip-search-face)
  2548.         "*Face used to flash out the search pattern.")
  2549.     ))
  2550.   
  2551.   
  2552. (defun vip-set-minibuffer-faces ()
  2553.   (if (not (vip-has-face-support-p))
  2554.       ()
  2555.     (defvar vip-minibuffer-emacs-face
  2556.       (progn
  2557.     (make-face 'vip-minibuffer-emacs-face)
  2558.     (vip-hide-face 'vip-minibuffer-emacs-face)
  2559.     (or (face-differs-from-default-p 'vip-minibuffer-emacs-face)
  2560.         ;; face wasn't set in .vip or .Xdefaults
  2561.         (if vip-vi-style-in-minibuffer
  2562.         ;; emacs state is an exception in the minibuffer
  2563.         (if (vip-can-use-colors "darkseagreen2" "Black")
  2564.             (progn
  2565.               (set-face-background
  2566.                'vip-minibuffer-emacs-face "darkseagreen2")
  2567.               (set-face-foreground
  2568.                'vip-minibuffer-emacs-face "Black"))
  2569.           (copy-face 'modeline 'vip-minibuffer-emacs-face))
  2570.           ;; emacs state is the main state in the minibuffer
  2571.           (if (vip-can-use-colors "Black" "pink")
  2572.           (progn
  2573.             (set-face-background 'vip-minibuffer-emacs-face "pink") 
  2574.             (set-face-foreground
  2575.              'vip-minibuffer-emacs-face "Black"))
  2576.         (copy-face 'italic 'vip-minibuffer-emacs-face))
  2577.           ))
  2578.     'vip-minibuffer-emacs-face)
  2579.       "Face used in the Minibuffer when it is in Emacs state.")
  2580.     
  2581.     (defvar vip-minibuffer-insert-face
  2582.       (progn
  2583.     (make-face 'vip-minibuffer-insert-face)
  2584.     (vip-hide-face 'vip-minibuffer-insert-face)
  2585.     (or (face-differs-from-default-p 'vip-minibuffer-insert-face)
  2586.         (if vip-vi-style-in-minibuffer
  2587.         (if (vip-can-use-colors "Black" "pink")
  2588.             (progn
  2589.               (set-face-background 'vip-minibuffer-insert-face "pink") 
  2590.               (set-face-foreground
  2591.                'vip-minibuffer-insert-face "Black"))
  2592.           (copy-face 'italic 'vip-minibuffer-insert-face))
  2593.           ;; If Insert state is an exception
  2594.           (if (vip-can-use-colors "darkseagreen2" "Black")
  2595.           (progn
  2596.             (set-face-background
  2597.              'vip-minibuffer-insert-face "darkseagreen2")
  2598.             (set-face-foreground
  2599.              'vip-minibuffer-insert-face "Black"))
  2600.         (copy-face 'modeline 'vip-minibuffer-insert-face))
  2601.           (vip-italicize-face 'vip-minibuffer-insert-face)))
  2602.     'vip-minibuffer-insert-face)
  2603.       "Face used in the Minibuffer when it is in Insert state.")
  2604.     
  2605.     (defvar vip-minibuffer-vi-face
  2606.       (progn
  2607.     (make-face 'vip-minibuffer-vi-face)
  2608.     (vip-hide-face 'vip-minibuffer-vi-face)
  2609.     (or (face-differs-from-default-p 'vip-minibuffer-vi-face)
  2610.         (if vip-vi-style-in-minibuffer
  2611.         (if (vip-can-use-colors "Black" "grey")
  2612.             (progn
  2613.               (set-face-background 'vip-minibuffer-vi-face "grey")
  2614.               (set-face-foreground 'vip-minibuffer-vi-face "Black"))
  2615.           (copy-face 'bold 'vip-minibuffer-vi-face))
  2616.           (copy-face 'bold 'vip-minibuffer-vi-face)
  2617.           (invert-face 'vip-minibuffer-vi-face)))
  2618.     'vip-minibuffer-vi-face)
  2619.       "Face used in the Minibuffer when it is in Vi state.")
  2620.     
  2621.     ;; the current face used in the minibuffer
  2622.     (vip-deflocalvar vip-minibuffer-current-face vip-minibuffer-emacs-face "")
  2623.     ))
  2624.     
  2625.   
  2626.  
  2627. ;;; Reading string with history  
  2628.     
  2629. (defun vip-read-string-with-history (prompt &optional initial 
  2630.                         history-var default keymap)
  2631.   ;; Read string, prompting with PROMPT and inserting the INITIAL
  2632.   ;; value. Uses HISTORY-VAR. DEFAULT is the default value to accept if the
  2633.   ;; input is an empty string. Use KEYMAP, if given, or the
  2634.   ;; minibuffer-local-map.
  2635.   ;; Default value is displayed until the user types something in the
  2636.   ;; minibuffer. 
  2637.   (let ((minibuffer-setup-hook 
  2638.      '(lambda ()
  2639.         (if (stringp initial)
  2640.         (progn
  2641.           ;; don't wait if we have unread events or in kbd macro
  2642.           (or unread-command-events
  2643.               executing-kbd-macro
  2644.               (sit-for 840))
  2645.           (erase-buffer)
  2646.           (insert initial)))
  2647.         (vip-minibuffer-setup-sentinel)))
  2648.     (val "")
  2649.     (padding "")
  2650.     temp-msg)
  2651.     
  2652.     (setq keymap (or keymap minibuffer-local-map)
  2653.       initial (or initial "")
  2654.       temp-msg (if default
  2655.                (format "(default: %s) " default)
  2656.              ""))
  2657.            
  2658.     (setq vip-incomplete-ex-cmd nil)
  2659.     (setq val (read-from-minibuffer prompt 
  2660.                     (concat temp-msg initial val padding)
  2661.                     keymap nil history-var))
  2662.     (setq minibuffer-setup-hook nil
  2663.       padding (vip-array-to-string (this-command-keys))
  2664.       temp-msg "")
  2665.     ;; the following tries to be smart about what to put in history
  2666.     (if (not (string= val (car (eval history-var))))
  2667.     (set history-var (cons val (eval history-var))))
  2668.     (if (or (string= (nth 0 (eval history-var)) (nth 1 (eval history-var)))
  2669.         (string= (nth 0 (eval history-var)) ""))
  2670.     (set history-var (cdr (eval history-var))))
  2671.     ;; If the user enters nothing but the prev cmd wasn't vip-ex,
  2672.     ;; vip-command-argument, or `! shell-command', this probably means 
  2673.     ;; that the user typed something then erased. Return "" in this case, not
  2674.     ;; the default---the default is too confusing in this case.
  2675.     (cond ((and (string= val "")
  2676.         (not (string= prompt "!")) ; was a `! shell-command'
  2677.         (not (memq last-command
  2678.                '(vip-ex
  2679.                  vip-command-argument
  2680.                  t)
  2681.                )))
  2682.        "")
  2683.       ((string= val "") (or default ""))
  2684.       (t val))
  2685.     ))
  2686.   
  2687.  
  2688.  
  2689. ;; insertion commands
  2690.  
  2691. ;; Called when state changes from Insert Vi command mode.
  2692. ;; Repeats the insertion command if Insert state was entered with prefix
  2693. ;; argument > 1.
  2694. (defun vip-repeat-insert-command ()
  2695.   (let ((i-com (car vip-d-com))
  2696.     (val   (nth 1 vip-d-com))
  2697.     (char  (nth 2 vip-d-com)))
  2698.     (if (and val (> val 1)) ; first check that val is non-nil
  2699.     (progn        
  2700.       (setq vip-d-com (list i-com (1- val) ?r nil nil nil))
  2701.       (vip-repeat nil)
  2702.       (setq vip-d-com (list i-com val char nil nil nil))
  2703.       ))))
  2704.  
  2705. (defun vip-insert (arg)
  2706.   "Insert before point."
  2707.   (interactive "P")
  2708.   (vip-set-complex-command-for-undo)
  2709.   (let ((val (vip-p-val arg))
  2710.     (com (vip-getcom arg)))
  2711.     (vip-set-destructive-command (list 'vip-insert val ?r nil nil nil))
  2712.     (if com
  2713.     (vip-loop val (vip-yank-last-insertion))
  2714.       (vip-change-state-to-insert))))
  2715.  
  2716. (defun vip-append (arg)
  2717.   "Append after point."
  2718.   (interactive "P")
  2719.   (vip-set-complex-command-for-undo)
  2720.   (let ((val (vip-p-val arg))
  2721.     (com (vip-getcom arg)))
  2722.     (vip-set-destructive-command (list 'vip-append val ?r nil nil nil))
  2723.     (if (not (eolp)) (forward-char))
  2724.     (if (equal com ?r)
  2725.     (vip-loop val (vip-yank-last-insertion))
  2726.       (vip-change-state-to-insert))))
  2727.  
  2728. (defun vip-Append (arg)
  2729.   "Append at end of line."
  2730.   (interactive "P")
  2731.   (vip-set-complex-command-for-undo)
  2732.   (let ((val (vip-p-val arg))
  2733.     (com (vip-getcom arg)))
  2734.     (vip-set-destructive-command (list 'vip-Append val ?r nil nil nil))
  2735.     (end-of-line)
  2736.     (if (equal com ?r)
  2737.     (vip-loop val (vip-yank-last-insertion))
  2738.       (vip-change-state-to-insert))))
  2739.  
  2740. (defun vip-Insert (arg)
  2741.   "Insert before first non-white."
  2742.   (interactive "P")
  2743.   (vip-set-complex-command-for-undo)
  2744.   (let ((val (vip-p-val arg))
  2745.     (com (vip-getcom arg)))
  2746.     (vip-set-destructive-command (list 'vip-Insert val ?r nil nil nil))
  2747.     (back-to-indentation)
  2748.     (if (equal com ?r)
  2749.     (vip-loop val (vip-yank-last-insertion))
  2750.       (vip-change-state-to-insert))))
  2751.  
  2752. (defun vip-open-line (arg)
  2753.   "Open line below."
  2754.   (interactive "P")
  2755.   (vip-set-complex-command-for-undo)
  2756.   (let ((val (vip-p-val arg))
  2757.     (com (vip-getcom arg)))
  2758.     (vip-set-destructive-command (list 'vip-open-line val ?r nil nil nil))
  2759.     (let ((col (current-indentation)))
  2760.       (if (equal com ?r)
  2761.       (vip-loop val
  2762.             (progn
  2763.               (end-of-line)
  2764.               (newline 1)
  2765.               (if vip-auto-indent 
  2766.               (progn
  2767.                 (setq vip-cted t)
  2768.                 (if vip-electric-mode
  2769.                 (indent-according-to-mode)
  2770.                   (indent-to col))
  2771.                 ))
  2772.               (vip-yank-last-insertion)))
  2773.     (end-of-line)
  2774.     (newline 1)
  2775.     (if vip-auto-indent
  2776.         (progn
  2777.           (setq vip-cted t)
  2778.           (if vip-electric-mode
  2779.           (indent-according-to-mode)
  2780.         (indent-to col))
  2781.           ))
  2782.     (vip-change-state-to-insert)
  2783.     ))))
  2784.  
  2785. (defun vip-Open-line (arg)
  2786.   "Open line above."
  2787.   (interactive "P")
  2788.   (vip-set-complex-command-for-undo)
  2789.   (let ((val (vip-p-val arg))
  2790.     (com (vip-getcom arg)))
  2791.     (vip-set-destructive-command (list 'vip-Open-line val ?r nil nil nil))
  2792.     (let ((col (current-indentation)))
  2793.       (if (equal com ?r)
  2794.       (vip-loop val
  2795.             (progn
  2796.               (beginning-of-line)
  2797.               (open-line 1)
  2798.               (if vip-auto-indent 
  2799.               (progn
  2800.                 (setq vip-cted t)
  2801.                 (if vip-electric-mode
  2802.                 (indent-according-to-mode)
  2803.                   (indent-to col))
  2804.                 ))
  2805.               (vip-yank-last-insertion)))
  2806.     (beginning-of-line)
  2807.     (open-line 1)
  2808.     (if vip-auto-indent
  2809.         (progn
  2810.           (setq vip-cted t)
  2811.           (if vip-electric-mode
  2812.           (indent-according-to-mode)
  2813.         (indent-to col))
  2814.           ))
  2815.     (vip-change-state-to-insert)))))
  2816.  
  2817. (defun vip-open-line-at-point (arg)
  2818.   "Open line at point."
  2819.   (interactive "P")
  2820.   (vip-set-complex-command-for-undo)
  2821.   (let ((val (vip-p-val arg))
  2822.     (com (vip-getcom arg)))
  2823.     (vip-set-destructive-command
  2824.      (list 'vip-open-line-at-point val ?r nil nil nil))
  2825.     (if (equal com ?r)
  2826.     (vip-loop val
  2827.           (progn
  2828.             (open-line 1)
  2829.             (vip-yank-last-insertion)))
  2830.       (open-line 1)
  2831.       (vip-change-state-to-insert))))
  2832.  
  2833. (defun vip-substitute (arg)
  2834.   "Substitute characters."
  2835.   (interactive "P")
  2836.   (let ((val (vip-p-val arg))
  2837.     (com (vip-getcom arg)))
  2838.     (push-mark nil t)
  2839.     (forward-char val)
  2840.     (if (equal com ?r)
  2841.     (vip-change-subr (mark t) (point))
  2842.       (vip-change (mark t) (point)))
  2843.     (vip-set-destructive-command (list 'vip-substitute val ?r nil nil nil))
  2844.     ))
  2845.  
  2846. (defun vip-substitute-line (arg)
  2847.   "Substitute lines."
  2848.   (interactive "p")
  2849.   (vip-set-complex-command-for-undo)
  2850.   (vip-line (cons arg ?C)))
  2851.  
  2852. ;; Prepare for replace
  2853. (defun vip-start-replace ()
  2854.   (setq vip-began-as-replace t
  2855.     vip-sitting-in-replace t
  2856.     vip-replace-chars-to-delete 0
  2857.     vip-replace-chars-deleted 0)
  2858.   (vip-add-hook 'vip-after-change-functions 'vip-replace-mode-spy-after t)
  2859.   (vip-add-hook 'vip-before-change-functions 'vip-replace-mode-spy-before t)
  2860.   ;; this will get added repeatedly, but no harm
  2861.   (add-hook 'after-change-functions 'vip-after-change-sentinel t)
  2862.   (add-hook 'before-change-functions 'vip-before-change-sentinel t)
  2863.   (vip-move-marker-locally 'vip-last-posn-in-replace-region
  2864.                (vip-replace-start))
  2865.   (vip-add-hook
  2866.    'vip-post-command-hooks 'vip-replace-state-post-command-sentinel t)
  2867.   (vip-add-hook
  2868.    'vip-pre-command-hooks 'vip-replace-state-pre-command-sentinel t)
  2869.   )
  2870.   
  2871.  
  2872. ;; checks how many chars were deleted by the last change
  2873. (defun vip-replace-mode-spy-before (beg end)
  2874.   (setq vip-replace-chars-deleted
  2875.     (- end beg
  2876.        (max 0 (- end (vip-replace-end)))
  2877.        (max 0 (- (vip-replace-start) beg))
  2878.        )))
  2879.  
  2880. ;; Invoked as an after-change-function to set up parameters of the last change
  2881. (defun vip-replace-mode-spy-after (beg end length)
  2882.   (if (memq vip-intermediate-command '(repeating-insertion-from-ring))
  2883.       (progn
  2884.     (setq vip-replace-chars-to-delete 0)
  2885.     (vip-move-marker-locally 
  2886.      'vip-last-posn-in-replace-region (point)))
  2887.     
  2888.     (let (beg-col end-col real-end chars-to-delete)
  2889.       (setq real-end (min end (vip-replace-end)))
  2890.       (save-excursion
  2891.     (goto-char beg)
  2892.     (setq beg-col (current-column))
  2893.     (goto-char real-end)
  2894.     (setq end-col (current-column)))
  2895.       
  2896.       ;; If beg of change is outside the replacement region, then don't
  2897.       ;; delete anything in the repl region (set chars-to-delete to 0).
  2898.       ;;
  2899.       ;; This works fine except that we have to take special care of
  2900.       ;; dabbrev-expand.  The problem stems from new-dabbrev.el, which
  2901.       ;; sometimes simply shifts the repl region rightwards, without
  2902.       ;; deleting an equal amount of characters.
  2903.       ;;
  2904.       ;; The reason why new-dabbrev.el causes this are this:
  2905.       ;; if one dinamically completes a partial word that starts before the
  2906.       ;; replacement region (but ends inside) then new-dabbrev.el first
  2907.       ;; moves cursor backwards, to the beginning of the word to be
  2908.       ;; completed (say, pt A). Then it inserts the 
  2909.       ;; completed word and then deletes the old, incomplete part.
  2910.       ;; Since the complete word is inserted at position before the repl
  2911.       ;; region, the next If-statement would have set chars-to-delete to 0
  2912.       ;; unless we check for the current command, which must be
  2913.       ;; dabbrev-expand.
  2914.       ;;
  2915.       ;; In fact, it might be also useful to have overlays for insert
  2916.       ;; regions as well, since this will let us capture the situation when
  2917.       ;; dabbrev-expand goes back past the insertion point to find the
  2918.       ;; beginning of the word to be expanded.
  2919.       (if (or (and (<= (vip-replace-start) beg)
  2920.            (<= beg (vip-replace-end)))
  2921.           (and (= length 0) (eq this-command 'dabbrev-expand)))
  2922.       (setq chars-to-delete
  2923.         (max (- end-col beg-col) (- real-end beg) 0))
  2924.     (setq chars-to-delete 0))
  2925.       
  2926.       ;; if beg = last change position, it means that we are within the
  2927.       ;; same command that does multiple changes. Moreover, it means
  2928.       ;; that we have two subsequent changes (insert/delete) that
  2929.       ;; complement each other.
  2930.       (if (= beg (marker-position vip-last-posn-in-replace-region))
  2931.       (setq vip-replace-chars-to-delete 
  2932.         (- (+ chars-to-delete vip-replace-chars-to-delete)
  2933.            vip-replace-chars-deleted)) 
  2934.     (setq vip-replace-chars-to-delete chars-to-delete))
  2935.       
  2936.       (vip-move-marker-locally 
  2937.        'vip-last-posn-in-replace-region
  2938.        (max (if (> end (vip-replace-end)) (vip-replace-start) end)
  2939.         (or (marker-position vip-last-posn-in-replace-region)
  2940.         (vip-replace-start)) 
  2941.         ))
  2942.       
  2943.       (setq vip-replace-chars-to-delete
  2944.         (max 0 (min vip-replace-chars-to-delete
  2945.             (- (vip-replace-end)
  2946.                vip-last-posn-in-replace-region))))
  2947.       )))
  2948.  
  2949.  
  2950. ;; Delete stuff between posn and the end of vip-replace-overlay-marker, if
  2951. ;; posn is within the overlay.
  2952. (defun vip-finish-change (posn)
  2953.   (vip-remove-hook 'vip-after-change-functions 'vip-replace-mode-spy-after)
  2954.   (vip-remove-hook 'vip-before-change-functions 'vip-replace-mode-spy-before)
  2955.   (vip-remove-hook 'vip-post-command-hooks
  2956.            'vip-replace-state-post-command-sentinel) 
  2957.   (vip-remove-hook
  2958.    'vip-pre-command-hooks 'vip-replace-state-pre-command-sentinel) 
  2959.   (vip-restore-cursor-color)
  2960.   (setq vip-sitting-in-replace nil) ; just in case we'll need to know it
  2961.   (save-excursion
  2962.     (if (and 
  2963.      vip-replace-overlay
  2964.      (>= posn (vip-replace-start))
  2965.      (<  posn (vip-replace-end)))
  2966.        (delete-region posn (vip-replace-end)))
  2967.     )
  2968.   
  2969.   (if (eq vip-current-state 'replace-state)
  2970.       (vip-downgrade-to-insert))
  2971.   ;; replace mode ended => nullify vip-last-posn-in-replace-region
  2972.   (vip-move-marker-locally 'vip-last-posn-in-replace-region nil)
  2973.   (vip-hide-replace-overlay)
  2974.   (vip-refresh-mode-line)
  2975.   (vip-put-string-on-kill-ring vip-last-replace-region)
  2976.   )
  2977.  
  2978. ;; Make STRING be the first element of the kill ring.
  2979. (defun vip-put-string-on-kill-ring (string)
  2980.   (setq kill-ring (cons string kill-ring))
  2981.   (if (> (length kill-ring) kill-ring-max)
  2982.       (setcdr (nthcdr (1- kill-ring-max) kill-ring) nil))
  2983.   (setq kill-ring-yank-pointer kill-ring))
  2984.  
  2985. (defun vip-finish-R-mode ()
  2986.   (vip-remove-hook 'vip-post-command-hooks 'vip-R-state-post-command-sentinel)
  2987.   (vip-remove-hook
  2988.    'vip-pre-command-hooks 'vip-replace-state-pre-command-sentinel)
  2989.   (vip-downgrade-to-insert))
  2990.   
  2991. (defun vip-start-R-mode ()
  2992.   ;; Leave arg as 1, not t: XEmacs insists that it must be a pos number
  2993.   (overwrite-mode 1)
  2994.   (vip-add-hook
  2995.    'vip-post-command-hooks 'vip-R-state-post-command-sentinel t)
  2996.   (vip-add-hook
  2997.    'vip-pre-command-hooks 'vip-replace-state-pre-command-sentinel t)
  2998.   )
  2999.  
  3000.  
  3001.   
  3002. (defun vip-replace-state-exit-cmd ()
  3003.   "Binding for keys that cause Replace state to switch to Vi or to Insert.
  3004. These keys are ESC, RET, and LineFeed"
  3005.   (interactive)
  3006.   (if overwrite-mode  ;; If you are in replace mode invoked via 'R'
  3007.       (vip-finish-R-mode)
  3008.     (vip-finish-change vip-last-posn-in-replace-region))
  3009.   (let (com)
  3010.     (if (eq this-command 'vip-intercept-ESC-key)
  3011.     (setq com 'vip-exit-insert-state)
  3012.       (vip-set-unread-command-events last-input-char)
  3013.       (setq com (key-binding (read-key-sequence nil))))
  3014.       
  3015.     (condition-case conds
  3016.     (command-execute com)
  3017.       (error
  3018.        (vip-message-conditions conds)))
  3019.     )
  3020.   (vip-hide-replace-overlay))
  3021.  
  3022.   
  3023. ;; This is the function bound to 'R'---unlimited replace.
  3024. ;; Similar to Emacs's own overwrite-mode.
  3025. (defun vip-overwrite (arg) 
  3026.   "Begin overwrite mode."
  3027.   (interactive "P")
  3028.   (let ((val (vip-p-val arg))
  3029.     (com (vip-getcom arg)) (len))
  3030.     (vip-set-destructive-command (list 'vip-overwrite val ?r nil nil nil))
  3031.     (if com
  3032.     (progn 
  3033.       ;; Viper saves inserted text in vip-last-insertion
  3034.       (setq len (length vip-last-insertion))
  3035.       (delete-char len)    
  3036.       (vip-loop val (vip-yank-last-insertion)))
  3037.       (setq last-command 'vip-overwrite)
  3038.       (vip-set-complex-command-for-undo)
  3039.       (vip-set-replace-overlay (point) (vip-line-pos 'end))
  3040.       (vip-change-state-to-replace)
  3041.       )))
  3042.  
  3043.  
  3044. ;; line commands
  3045.  
  3046. (defun vip-line (arg)
  3047.   (let ((val (car arg))
  3048.     (com (cdr arg)))
  3049.     (vip-move-marker-locally 'vip-com-point (point))
  3050.     (if (not (eobp))
  3051.     (vip-next-line-carefully (1- val)))
  3052.     ;; this ensures that dd, cc, D, yy will do the right thing on the last
  3053.     ;; line of buffer when this line has no \n.
  3054.     (vip-add-newline-at-eob-if-necessary)
  3055.     (vip-execute-com 'vip-line val com))
  3056.   (if (and (eobp) (not (bobp))) (forward-line -1))
  3057.   )
  3058.  
  3059. (defun vip-yank-line (arg)
  3060.   "Yank ARG lines (in Vi's sense)."
  3061.   (interactive "P")
  3062.   (let ((val (vip-p-val arg)))
  3063.     (vip-line (cons val ?Y))))
  3064.  
  3065.  
  3066. ;; region commands
  3067.  
  3068. (defun vip-region (arg)
  3069.   "Execute command on a region."
  3070.   (interactive "P")
  3071.   (let ((val (vip-P-val arg))
  3072.     (com (vip-getcom arg)))
  3073.     (vip-move-marker-locally 'vip-com-point (point))
  3074.     (exchange-point-and-mark)
  3075.     (vip-execute-com 'vip-region val com)))
  3076.  
  3077. (defun vip-Region (arg)
  3078.   "Execute command on a Region."
  3079.   (interactive "P")
  3080.   (let ((val (vip-P-val arg))
  3081.     (com (vip-getCom arg)))
  3082.     (vip-move-marker-locally 'vip-com-point (point))
  3083.     (exchange-point-and-mark)
  3084.     (vip-execute-com 'vip-Region val com)))
  3085.  
  3086. (defun vip-replace-char (arg)
  3087.   "Replace the following ARG chars by the character read."
  3088.   (interactive "P")
  3089.   (if (and (eolp) (bolp)) (error "No character to replace here"))
  3090.   (let ((val (vip-p-val arg))
  3091.     (com (vip-getcom arg)))
  3092.     (vip-replace-char-subr com val)
  3093.     (if (and (eolp) (not (bolp))) (forward-char 1))
  3094.     (vip-set-destructive-command
  3095.      (list 'vip-replace-char val ?r nil vip-d-char nil))
  3096.   ))
  3097.  
  3098. (defun vip-replace-char-subr (com arg)
  3099.   (let ((take-care-of-iso-accents
  3100.      (and (boundp 'iso-accents-mode) vip-automatic-iso-accents))
  3101.     char)
  3102.     (setq char (if (equal com ?r)
  3103.            vip-d-char
  3104.          (read-char)))
  3105.     (if (and  take-care-of-iso-accents (memq char '(?' ?\" ?^ ?~)))
  3106.     ;; get European characters
  3107.     (progn
  3108.       (iso-accents-mode 1)
  3109.       (vip-set-unread-command-events char)
  3110.       (setq char (aref (read-key-sequence nil) 0))
  3111.       (iso-accents-mode -1)))
  3112.     (delete-char arg t)
  3113.     (setq vip-d-char char)
  3114.     (vip-loop (if (> arg 0) arg (- arg)) 
  3115.         (if (eq char ?\C-m) (insert "\n") (insert char)))
  3116.     (backward-char arg)))
  3117.  
  3118.  
  3119. ;; basic cursor movement.  j, k, l, h commands.
  3120.  
  3121. (defun vip-forward-char (arg)
  3122.   "Move point right ARG characters (left if ARG negative).
  3123. On reaching end of line, stop and signal error."
  3124.   (interactive "P")
  3125.   (vip-leave-region-active)
  3126.   (let ((val (vip-p-val arg))
  3127.     (com (vip-getcom arg)))
  3128.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3129.     (if vip-ex-style-motion
  3130.     (progn
  3131.       ;; the boundary condition check gets weird here because
  3132.       ;; forward-char may be the parameter of a delete, and 'dl' works
  3133.       ;; just like 'x' for the last char on a line, so we have to allow
  3134.       ;; the forward motion before the 'vip-execute-com', but, of
  3135.       ;; course, 'dl' doesn't work on an empty line, so we have to
  3136.       ;; catch that condition before 'vip-execute-com'
  3137.       (if (and (eolp) (bolp)) (error "") (forward-char val))
  3138.       (if com (vip-execute-com 'vip-forward-char val com))
  3139.       (if (eolp) (progn (backward-char 1) (error ""))))
  3140.       (forward-char val)
  3141.       (if com (vip-execute-com 'vip-forward-char val com)))))
  3142.  
  3143. (defun vip-backward-char (arg)
  3144.   "Move point left ARG characters (right if ARG negative). 
  3145. On reaching beginning of line, stop and signal error."
  3146.   (interactive "P")
  3147.   (vip-leave-region-active)
  3148.   (let ((val (vip-p-val arg))
  3149.     (com (vip-getcom arg)))
  3150.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3151.     (if vip-ex-style-motion
  3152.     (progn
  3153.       (if (bolp) (error "") (backward-char val))
  3154.       (if com (vip-execute-com 'vip-backward-char val com)))
  3155.       (backward-char val)
  3156.       (if com (vip-execute-com 'vip-backward-char val com)))))
  3157.       
  3158. ;; Like forward-char, but doesn't move at end of buffer.
  3159. (defun vip-forward-char-carefully (&optional arg)      
  3160.   (setq arg (or arg 1))
  3161.   (if (>= (point-max) (+ (point) arg))
  3162.       (forward-char arg)
  3163.     (goto-char (point-max))))
  3164.       
  3165. ;; Like backward-char, but doesn't move at end of buffer.
  3166. (defun vip-backward-char-carefully (&optional arg)      
  3167.   (setq arg (or arg 1))
  3168.   (if (<= (point-min) (- (point) arg))
  3169.       (backward-char arg)
  3170.     (goto-char (point-min))))
  3171.  
  3172. (defun vip-next-line-carefully (arg)
  3173.   (condition-case nil
  3174.       (next-line arg)
  3175.     (error nil)))
  3176.  
  3177.  
  3178.  
  3179. ;;; Word command
  3180.  
  3181. ;; Words are formed from alpha's and nonalphas - <sp>,\t\n are separators
  3182. ;; for word movement. When executed with a destructive command, \n is
  3183. ;; usually left untouched for the last word.
  3184. ;; Viper uses syntax table to determine what is a word and what is a
  3185. ;; separator. However, \n is always a separator. Also, if vip-syntax-preference
  3186. ;; is 'vi, then `_' is part of the word.
  3187.  
  3188. ;; skip only one \n
  3189. (defun vip-skip-separators (forward)
  3190.   (if forward
  3191.       (progn
  3192.     (vip-skip-all-separators-forward 'within-line)
  3193.     (if (looking-at "\n")
  3194.         (progn
  3195.           (forward-char)
  3196.           (vip-skip-all-separators-forward  'within-line))))
  3197.     (vip-skip-all-separators-backward 'within-line)
  3198.     (backward-char)
  3199.     (if (looking-at "\n")
  3200.     (vip-skip-all-separators-backward 'within-line)
  3201.       (forward-char))))
  3202.       
  3203. (defun vip-forward-word-kernel (val)
  3204.   (while (> val 0)
  3205.     (cond ((vip-looking-at-alpha)
  3206.        (vip-skip-alpha-forward "_")
  3207.        (vip-skip-separators t))
  3208.       ((vip-looking-at-separator)
  3209.        (vip-skip-separators t))
  3210.       ((not (vip-looking-at-alphasep))
  3211.        (vip-skip-nonalphasep-forward)
  3212.        (vip-skip-separators t)))
  3213.     (setq val (1- val))))
  3214.  
  3215. ;; first search backward for pat. Then skip chars backwards using aux-pat
  3216. (defun vip-fwd-skip (pat aux-pat lim)
  3217.   (if (and (save-excursion 
  3218.          (re-search-backward pat lim t))
  3219.        (= (point) (match-end 0)))
  3220.       (goto-char (match-beginning 0)))
  3221.   (skip-chars-backward aux-pat lim)
  3222.   (if (= (point) lim)
  3223.       (vip-forward-char-carefully))
  3224.   )
  3225.  
  3226.       
  3227. (defun vip-forward-word (arg)
  3228.   "Forward word."
  3229.   (interactive "P")
  3230.   (vip-leave-region-active)
  3231.   (let ((val (vip-p-val arg))
  3232.     (com (vip-getcom arg)))
  3233.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3234.     (vip-forward-word-kernel val)
  3235.     (if com (progn
  3236.           (cond ((memq com (list ?c (- ?c)))
  3237.              (vip-fwd-skip "\n[ \t]*" " \t" vip-com-point))
  3238.             ;; Yank words including the whitespace, but not newline
  3239.             ((memq com (list ?y (- ?y)))
  3240.              (vip-fwd-skip "\n[ \t]*" "" vip-com-point))
  3241.             ((vip-dotable-command-p com)
  3242.              (vip-fwd-skip "\n[ \t]*" "" vip-com-point)))
  3243.           (vip-execute-com 'vip-forward-word val com)))))
  3244.       
  3245.  
  3246. (defun vip-forward-Word (arg)
  3247.   "Forward word delimited by white characters."
  3248.   (interactive "P")
  3249.   (vip-leave-region-active)
  3250.   (let ((val (vip-p-val arg))
  3251.     (com (vip-getcom arg)))
  3252.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3253.     (vip-loop val
  3254.           (progn
  3255.         (vip-skip-nonseparators 'forward)
  3256.         (vip-skip-separators t)))
  3257.     (if com (progn
  3258.           (cond ((memq com (list ?c (- ?c)))
  3259.              (vip-fwd-skip "\n[ \t]*" " \t" vip-com-point))
  3260.             ;; Yank words including the whitespace, but not newline
  3261.             ((memq com (list ?y (- ?y)))
  3262.              (vip-fwd-skip "\n[ \t]*" "" vip-com-point))
  3263.             ((vip-dotable-command-p com)
  3264.              (vip-fwd-skip "\n[ \t]*" "" vip-com-point)))
  3265.           (vip-execute-com 'vip-forward-Word val com)))))
  3266.  
  3267.  
  3268. ;; this is a bit different from Vi, but Vi's end of word 
  3269. ;; makes no sense whatsoever
  3270. (defun vip-end-of-word-kernel ()
  3271.   (if (vip-end-of-word-p) (forward-char))
  3272.   (if (vip-looking-at-separator)
  3273.       (vip-skip-all-separators-forward))
  3274.   
  3275.   (cond ((vip-looking-at-alpha) (vip-skip-alpha-forward "_"))
  3276.     ((not (vip-looking-at-alphasep)) (vip-skip-nonalphasep-forward)))
  3277.   (vip-backward-char-carefully))
  3278.  
  3279. (defun vip-end-of-word-p ()
  3280.   (or (eobp) 
  3281.       (save-excursion
  3282.     (cond ((vip-looking-at-alpha)
  3283.            (forward-char)
  3284.            (not (vip-looking-at-alpha)))
  3285.           ((not (vip-looking-at-alphasep))
  3286.            (forward-char)
  3287.            (vip-looking-at-alphasep))))))
  3288.  
  3289.  
  3290. (defun vip-end-of-word (arg &optional careful)
  3291.   "Move point to end of current word."
  3292.   (interactive "P")
  3293.   (vip-leave-region-active)
  3294.   (let ((val (vip-p-val arg))
  3295.     (com (vip-getcom arg)))
  3296.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3297.     (vip-loop val (vip-end-of-word-kernel))
  3298.     (if com 
  3299.     (progn
  3300.       (forward-char)
  3301.       (vip-execute-com 'vip-end-of-word val com)))))
  3302.  
  3303. (defun vip-end-of-Word (arg)
  3304.   "Forward to end of word delimited by white character."
  3305.   (interactive "P")
  3306.   (vip-leave-region-active)
  3307.   (let ((val (vip-p-val arg))
  3308.     (com (vip-getcom arg)))
  3309.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3310.     (vip-loop val
  3311.           (progn
  3312.         (vip-end-of-word-kernel)
  3313.         (vip-skip-nonseparators 'forward)
  3314.         (backward-char)))
  3315.     (if com 
  3316.     (progn
  3317.       (forward-char)
  3318.       (vip-execute-com 'vip-end-of-Word val com)))))
  3319.  
  3320. (defun vip-backward-word-kernel (val)
  3321.   (while (> val 0)
  3322.     (backward-char)
  3323.     (cond ((vip-looking-at-alpha)
  3324.        (vip-skip-alpha-backward "_"))
  3325.       ((vip-looking-at-separator)
  3326.        (forward-char)
  3327.        (vip-skip-separators nil)
  3328.        (backward-char)
  3329.        (cond ((vip-looking-at-alpha)
  3330.           (vip-skip-alpha-backward "_"))
  3331.          ((not (vip-looking-at-alphasep))
  3332.           (vip-skip-nonalphasep-backward))
  3333.          (t (forward-char))))
  3334.       ((not (vip-looking-at-alphasep))
  3335.        (vip-skip-nonalphasep-backward)))
  3336.     (setq val (1- val))))
  3337.  
  3338. (defun vip-backward-word (arg)
  3339.   "Backward word."
  3340.   (interactive "P")
  3341.   (vip-leave-region-active)
  3342.   (let ((val (vip-p-val arg))
  3343.     (com (vip-getcom arg)))
  3344.     (if com
  3345.     (let (i)
  3346.       (if (setq i (save-excursion (backward-char) (looking-at "\n")))
  3347.           (backward-char))
  3348.       (vip-move-marker-locally 'vip-com-point (point))
  3349.       (if i (forward-char))))
  3350.     (vip-backward-word-kernel val)
  3351.     (if com (vip-execute-com 'vip-backward-word val com))))
  3352.  
  3353. (defun vip-backward-Word (arg)
  3354.   "Backward word delimited by white character."
  3355.   (interactive "P")
  3356.   (vip-leave-region-active)
  3357.   (let ((val (vip-p-val arg))
  3358.     (com (vip-getcom arg)))
  3359.     (if com
  3360.     (let (i)
  3361.       (if (setq i (save-excursion (backward-char) (looking-at "\n")))
  3362.           (backward-char))
  3363.       (vip-move-marker-locally 'vip-com-point (point))
  3364.       (if i (forward-char))))
  3365.     (vip-loop val
  3366.           (progn 
  3367.         (vip-skip-separators nil)
  3368.         (vip-skip-nonseparators 'backward)))
  3369.     (if com (vip-execute-com 'vip-backward-Word val com))))
  3370.  
  3371.  
  3372.  
  3373. ;; line commands
  3374.  
  3375. (defun vip-beginning-of-line (arg)
  3376.   "Go to beginning of line."
  3377.   (interactive "P")
  3378.   (vip-leave-region-active)
  3379.   (let ((val (vip-p-val arg))
  3380.     (com (vip-getcom arg)))
  3381.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3382.     (beginning-of-line val)
  3383.     (if com (vip-execute-com 'vip-beginning-of-line val com))))
  3384.  
  3385. (defun vip-bol-and-skip-white (arg)
  3386.   "Beginning of line at first non-white character."
  3387.   (interactive "P")
  3388.   (vip-leave-region-active)
  3389.   (let ((val (vip-p-val arg))
  3390.     (com (vip-getcom arg)))
  3391.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3392.     (forward-to-indentation (1- val))
  3393.     (if com (vip-execute-com 'vip-bol-and-skip-white val com))))
  3394.  
  3395. (defun vip-goto-eol (arg)
  3396.   "Go to end of line."
  3397.   (interactive "P")
  3398.   (vip-leave-region-active)
  3399.   (let ((val (vip-p-val arg))
  3400.     (com (vip-getcom arg)))
  3401.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3402.     (end-of-line val)
  3403.     (if com (vip-execute-com 'vip-goto-eol val com))
  3404.     (if vip-ex-style-motion
  3405.     (if (and (eolp) (not (bolp)) 
  3406.          ;; a fix for vip-change-to-eol
  3407.          (not (equal vip-current-state 'insert-state)))
  3408.         (backward-char 1)
  3409.     ))))
  3410.  
  3411.  
  3412. (defun vip-goto-col (arg)
  3413.   "Go to ARG's column."
  3414.   (interactive "P")
  3415.   (vip-leave-region-active)
  3416.   (let ((val (vip-p-val arg))
  3417.     (com (vip-getcom arg)))
  3418.     (save-excursion
  3419.       (end-of-line)
  3420.       (if (> val (1+ (current-column))) (error "")))
  3421.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3422.     (beginning-of-line)
  3423.     (forward-char (1- val))
  3424.     (if com (vip-execute-com 'vip-goto-col val com))))
  3425.     
  3426.  
  3427. (defun vip-next-line (arg)
  3428.   "Go to next line."
  3429.   (interactive "P")
  3430.   (vip-leave-region-active)
  3431.   (let ((val (vip-p-val arg))
  3432.     (com (vip-getCom arg)))
  3433.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3434.     (next-line val)
  3435.     (if vip-ex-style-motion
  3436.     (if (and (eolp) (not (bolp))) (backward-char 1)))
  3437.     (setq this-command 'next-line)
  3438.     (if com (vip-execute-com 'vip-next-line val com))))
  3439.  
  3440. (defun vip-next-line-at-bol (arg)
  3441.   "Next line at beginning of line."
  3442.   (interactive "P")
  3443.   (vip-leave-region-active)
  3444.   (save-excursion
  3445.     (end-of-line)
  3446.     (if (eobp) (error "Last line in buffer")))
  3447.   (let ((val (vip-p-val arg))
  3448.     (com (vip-getCom arg)))
  3449.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3450.     (forward-line val)
  3451.     (back-to-indentation)
  3452.     (if com (vip-execute-com 'vip-next-line-at-bol val com))))
  3453.  
  3454. (defun vip-previous-line (arg)     
  3455.   "Go to previous line."        
  3456.   (interactive "P")
  3457.   (vip-leave-region-active)
  3458.   (let ((val (vip-p-val arg))
  3459.     (com (vip-getCom arg)))
  3460.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3461.     (previous-line val)
  3462.     (if vip-ex-style-motion
  3463.     (if (and (eolp) (not (bolp))) (backward-char 1)))
  3464.     (setq this-command 'previous-line)
  3465.     (if com (vip-execute-com 'vip-previous-line val com))))
  3466.  
  3467.  
  3468. (defun vip-previous-line-at-bol (arg)
  3469.   "Previous line at beginning of line."
  3470.   (interactive "P")
  3471.   (vip-leave-region-active)
  3472.   (save-excursion
  3473.     (beginning-of-line)
  3474.     (if (bobp) (error "First line in buffer")))
  3475.   (let ((val (vip-p-val arg))
  3476.     (com (vip-getCom arg)))
  3477.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3478.     (forward-line (- val))
  3479.     (back-to-indentation)
  3480.     (if com (vip-execute-com 'vip-previous-line val com))))
  3481.  
  3482. (defun vip-change-to-eol (arg)
  3483.   "Change to end of line."
  3484.   (interactive "P")
  3485.   (vip-goto-eol (cons arg ?c)))
  3486.  
  3487. (defun vip-kill-line (arg)
  3488.   "Delete line."
  3489.   (interactive "P")
  3490.   (vip-goto-eol (cons arg ?d)))
  3491.  
  3492. (defun vip-erase-line (arg)
  3493.   "Erase line."
  3494.   (interactive "P")
  3495.   (vip-beginning-of-line (cons arg ?d)))
  3496.  
  3497.  
  3498. ;;; Moving around
  3499.  
  3500. (defun vip-goto-line (arg)
  3501.   "Go to ARG's line.  Without ARG go to end of buffer."
  3502.   (interactive "P")
  3503.   (let ((val (vip-P-val arg))
  3504.     (com (vip-getCom arg)))
  3505.     (vip-move-marker-locally 'vip-com-point (point))
  3506.     (vip-deactivate-mark)
  3507.     (push-mark nil t)
  3508.     (if (null val)
  3509.     (goto-char (point-max))
  3510.       (goto-char (point-min))
  3511.       (forward-line (1- val)))
  3512.     
  3513.     ;; positioning is done twice: before and after command execution
  3514.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3515.     (back-to-indentation)
  3516.     
  3517.     (if com (vip-execute-com 'vip-goto-line val com))
  3518.     
  3519.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3520.     (back-to-indentation)
  3521.     ))
  3522.  
  3523. ;; Find ARG's occurrence of CHAR on the current line. 
  3524. ;; If FORWARD then search is forward, otherwise backward.  OFFSET is used to
  3525. ;; adjust point after search.
  3526. (defun vip-find-char (arg char forward offset)
  3527.   (or (char-or-string-p char) (error ""))
  3528.   (let ((arg (if forward arg (- arg)))
  3529.     (cmd (if (eq vip-intermediate-command 'vip-repeat)
  3530.          (nth 5 vip-d-com)
  3531.            (vip-array-to-string (this-command-keys))))
  3532.     point)
  3533.     (save-excursion
  3534.       (save-restriction
  3535.     (if (> arg 0)
  3536.         (narrow-to-region
  3537.          ;; forward search begins here
  3538.          (if (eolp) (error "Command `%s':  At end of line" cmd) (point))
  3539.          ;; forward search ends here
  3540.          (progn (end-of-line) (point)))
  3541.       (narrow-to-region
  3542.        ;; backward search begins from here
  3543.        (if (bolp)
  3544.            (error "Command `%s':  At beginning of line" cmd) (point))
  3545.        ;; backward search ends here
  3546.        (progn (beginning-of-line) (point))))
  3547.     ;; if arg > 0, point is forwarded before search.
  3548.     (if (> arg 0) (goto-char (1+ (point-min)))
  3549.       (goto-char (point-max)))
  3550.     (if (let ((case-fold-search nil))
  3551.           (search-forward (char-to-string char) nil 0 arg))
  3552.         (setq point (point))
  3553.       (error "Command `%s':  `%c' not found" cmd char))))
  3554.     (goto-char (+ point (if (> arg 0) (if offset -2 -1) (if offset 1 0))))))
  3555.  
  3556. (defun vip-find-char-forward (arg)
  3557.   "Find char on the line. 
  3558. If called interactively read the char to find from the terminal, and if
  3559. called from vip-repeat, the char last used is used.  This behaviour is
  3560. controlled by the sign of prefix numeric value."
  3561.   (interactive "P")
  3562.   (let ((val (vip-p-val arg))
  3563.     (com (vip-getcom arg))
  3564.     (cmd-representation (nth 5 vip-d-com)))
  3565.     (if (> val 0)
  3566.     ;; this means that the function was called interactively
  3567.     (setq vip-f-char (read-char)
  3568.           vip-f-forward t
  3569.           vip-f-offset nil)
  3570.       ;; vip-repeat --- set vip-F-char from command-keys
  3571.       (setq vip-F-char (if (stringp cmd-representation)
  3572.                (vip-seq-last-elt cmd-representation)
  3573.              vip-F-char)
  3574.         vip-f-char vip-F-char)
  3575.       (setq val (- val)))
  3576.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3577.     (vip-find-char val (if (> (vip-p-val arg) 0) vip-f-char vip-F-char) t nil)
  3578.     (setq val (- val))
  3579.     (if com
  3580.     (progn
  3581.       (setq vip-F-char vip-f-char) ; set new vip-F-char
  3582.       (forward-char)
  3583.       (vip-execute-com 'vip-find-char-forward val com)))))
  3584.  
  3585. (defun vip-goto-char-forward (arg)
  3586.   "Go up to char ARG forward on line."
  3587.   (interactive "P")
  3588.   (let ((val (vip-p-val arg))
  3589.     (com (vip-getcom arg))
  3590.     (cmd-representation (nth 5 vip-d-com)))
  3591.     (if (> val 0)
  3592.     ;; this means that the function was called interactively
  3593.     (setq vip-f-char (read-char)
  3594.           vip-f-forward t
  3595.           vip-f-offset t)
  3596.       ;; vip-repeat --- set vip-F-char from command-keys
  3597.       (setq vip-F-char (if (stringp cmd-representation)
  3598.                (vip-seq-last-elt cmd-representation)
  3599.              vip-F-char)
  3600.         vip-f-char vip-F-char)
  3601.       (setq val (- val)))
  3602.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3603.     (vip-find-char val (if (> (vip-p-val arg) 0) vip-f-char vip-F-char) t t)
  3604.     (setq val (- val))
  3605.     (if com
  3606.     (progn
  3607.       (setq vip-F-char vip-f-char) ; set new vip-F-char
  3608.       (forward-char)
  3609.       (vip-execute-com 'vip-goto-char-forward val com)))))
  3610.  
  3611. (defun vip-find-char-backward (arg)
  3612.   "Find char ARG on line backward."
  3613.   (interactive "P")
  3614.   (let ((val (vip-p-val arg))
  3615.     (com (vip-getcom arg))
  3616.     (cmd-representation (nth 5 vip-d-com)))
  3617.     (if (> val 0)
  3618.     ;; this means that the function was called interactively
  3619.     (setq vip-f-char (read-char)
  3620.           vip-f-forward nil
  3621.           vip-f-offset nil)
  3622.       ;; vip-repeat --- set vip-F-char from command-keys
  3623.       (setq vip-F-char (if (stringp cmd-representation)
  3624.                (vip-seq-last-elt cmd-representation)
  3625.              vip-F-char)
  3626.         vip-f-char vip-F-char)
  3627.       (setq val (- val)))
  3628.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3629.     (vip-find-char
  3630.      val (if (> (vip-p-val arg) 0) vip-f-char vip-F-char) nil nil)
  3631.     (setq val (- val))
  3632.     (if com
  3633.     (progn
  3634.       (setq vip-F-char vip-f-char) ; set new vip-F-char
  3635.       (vip-execute-com 'vip-find-char-backward val com)))))
  3636.  
  3637. (defun vip-goto-char-backward (arg)
  3638.   "Go up to char ARG backward on line."
  3639.   (interactive "P")
  3640.   (let ((val (vip-p-val arg))
  3641.     (com (vip-getcom arg))
  3642.     (cmd-representation (nth 5 vip-d-com)))
  3643.     (if (> val 0)
  3644.     ;; this means that the function was called interactively
  3645.     (setq vip-f-char (read-char)
  3646.           vip-f-forward nil
  3647.           vip-f-offset t)
  3648.       ;; vip-repeat --- set vip-F-char from command-keys
  3649.       (setq vip-F-char (if (stringp cmd-representation)
  3650.                (vip-seq-last-elt cmd-representation)
  3651.              vip-F-char)
  3652.         vip-f-char vip-F-char)
  3653.       (setq val (- val)))
  3654.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3655.     (vip-find-char val (if (> (vip-p-val arg) 0) vip-f-char vip-F-char) nil t)
  3656.     (setq val (- val))
  3657.     (if com
  3658.     (progn
  3659.       (setq vip-F-char vip-f-char) ; set new vip-F-char
  3660.       (vip-execute-com 'vip-goto-char-backward val com)))))
  3661.  
  3662. (defun vip-repeat-find (arg)
  3663.   "Repeat previous find command."
  3664.   (interactive "P")
  3665.   (let ((val (vip-p-val arg))
  3666.     (com (vip-getcom arg)))
  3667.     (vip-deactivate-mark)
  3668.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3669.     (vip-find-char val vip-f-char vip-f-forward vip-f-offset)
  3670.     (if com
  3671.     (progn
  3672.       (if vip-f-forward (forward-char))
  3673.       (vip-execute-com 'vip-repeat-find val com)))))
  3674.  
  3675. (defun vip-repeat-find-opposite (arg)
  3676.   "Repeat previous find command in the opposite direction."
  3677.   (interactive "P")
  3678.   (let ((val (vip-p-val arg))
  3679.     (com (vip-getcom arg)))
  3680.     (vip-deactivate-mark)
  3681.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3682.     (vip-find-char val vip-f-char (not vip-f-forward) vip-f-offset)
  3683.     (if com
  3684.     (progn
  3685.       (if vip-f-forward (forward-char))
  3686.       (vip-execute-com 'vip-repeat-find-opposite val com)))))
  3687.  
  3688.  
  3689. ;; window scrolling etc.
  3690.  
  3691. (defun vip-other-window (arg)
  3692.   "Switch to other window."
  3693.   (interactive "p")
  3694.   (other-window arg)
  3695.   (or (not (eq vip-current-state 'emacs-state))
  3696.       (string= (buffer-name (current-buffer)) " *Minibuf-1*")
  3697.       (vip-change-state-to-vi)))
  3698.  
  3699. (defun vip-window-top (arg)
  3700.   "Go to home window line."
  3701.   (interactive "P")
  3702.   (let ((val (vip-p-val arg))
  3703.     (com (vip-getCom arg)))
  3704.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3705.     (push-mark nil t) 
  3706.     (move-to-window-line (1- val))
  3707.  
  3708.     ;; positioning is done twice: before and after command execution
  3709.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3710.     (back-to-indentation)
  3711.     
  3712.     (if com (vip-execute-com 'vip-window-top val com))
  3713.     
  3714.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3715.     (back-to-indentation)
  3716.     ))
  3717.  
  3718. (defun vip-window-middle (arg)
  3719.   "Go to middle window line."
  3720.   (interactive "P")
  3721.   (let ((val (vip-p-val arg))
  3722.     (com (vip-getCom arg))
  3723.     lines)
  3724.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3725.     (push-mark nil t) 
  3726.     (if (not (pos-visible-in-window-p (point-max)))
  3727.     (move-to-window-line (+ (/ (1- (window-height)) 2) (1- val)))
  3728.       (setq lines (count-lines (window-start) (point-max)))
  3729.       (move-to-window-line (+ (/ lines 2) (1- val))))
  3730.       
  3731.     ;; positioning is done twice: before and after command execution
  3732.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3733.     (back-to-indentation)
  3734.  
  3735.     (if com (vip-execute-com 'vip-window-middle val com))
  3736.     
  3737.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3738.     (back-to-indentation)
  3739.     ))
  3740.  
  3741. (defun vip-window-bottom (arg)
  3742.   "Go to last window line."
  3743.   (interactive "P")
  3744.   (let ((val (vip-p-val arg))
  3745.     (com (vip-getCom arg)))
  3746.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3747.     (push-mark nil t) 
  3748.     (move-to-window-line (- val))
  3749.     
  3750.     ;; positioning is done twice: before and after command execution
  3751.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3752.     (back-to-indentation)
  3753.  
  3754.     (if com (vip-execute-com 'vip-window-bottom val com))
  3755.     
  3756.     (if (and (eobp) (bolp) (not (bobp))) (forward-line -1))
  3757.     (back-to-indentation)
  3758.     ))
  3759.  
  3760. (defun vip-line-to-top (arg)
  3761.   "Put current line on the home line."
  3762.   (interactive "p")
  3763.   (recenter (1- arg)))
  3764.  
  3765. (defun vip-line-to-middle (arg)
  3766.   "Put current line on the middle line."
  3767.   (interactive "p")
  3768.   (recenter (+ (1- arg) (/ (1- (window-height)) 2))))
  3769.  
  3770. (defun vip-line-to-bottom (arg)
  3771.   "Put current line on the last line."
  3772.   (interactive "p")
  3773.   (recenter (- (window-height) (1+ arg))))
  3774.  
  3775.  
  3776. ;; paren match
  3777. ;; must correct this to only match ( to ) etc. On the other hand
  3778. ;; it is good that paren match gets confused, because that way you
  3779. ;; catch _all_ imbalances. 
  3780.  
  3781. (defun vip-paren-match (arg)
  3782.   "Go to the matching parenthesis."
  3783.   (interactive "P")
  3784.   (let ((com (vip-getcom arg))
  3785.     anchor-point)
  3786.     (if (integerp arg)
  3787.     (if (or (> arg 99) (< arg 1))
  3788.         (error "Prefix must be between 1 and 99")
  3789.       (goto-char
  3790.        (if (> (point-max) 80000)
  3791.            (* (/ (point-max) 100) arg)
  3792.          (/ (* (point-max) arg) 100)))
  3793.       (back-to-indentation))
  3794.       (let (beg-lim end-lim)
  3795.     (if (and (eolp) (not (bolp))) (forward-char -1))
  3796.     (if (not (looking-at "[][(){}]"))
  3797.         (setq anchor-point (point)))
  3798.     (save-excursion
  3799.       (beginning-of-line)
  3800.       (setq beg-lim (point))
  3801.       (end-of-line)
  3802.       (setq end-lim (point)))
  3803.     (cond ((re-search-forward "[][(){}]" end-lim t) 
  3804.            (backward-char) )
  3805.           ((re-search-backward "[][(){}]" beg-lim t))
  3806.           (t
  3807.            (error "No matching character on line"))))
  3808.       (cond ((looking-at "[\(\[{]")
  3809.          (if com (vip-move-marker-locally 'vip-com-point (point)))
  3810.          (forward-sexp 1)
  3811.          (if com
  3812.          (vip-execute-com 'vip-paren-match nil com)
  3813.            (backward-char)))
  3814.         (anchor-point
  3815.          (if com
  3816.          (progn
  3817.            (vip-move-marker-locally 'vip-com-point anchor-point)
  3818.            (forward-char 1)
  3819.            (vip-execute-com 'vip-paren-match nil com)
  3820.            )))
  3821.         ((looking-at "[])}]")
  3822.          (forward-char)
  3823.          (if com (vip-move-marker-locally 'vip-com-point (point)))
  3824.          (backward-sexp 1)
  3825.          (if com (vip-execute-com 'vip-paren-match nil com)))
  3826.         (t (error ""))))))
  3827.  
  3828.  
  3829. ;; sentence ,paragraph and heading
  3830.  
  3831. (defun vip-forward-sentence (arg)
  3832.   "Forward sentence."
  3833.   (interactive "P")
  3834.   (push-mark nil t) 
  3835.   (let ((val (vip-p-val arg))
  3836.     (com (vip-getcom arg)))
  3837.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3838.     (forward-sentence val)
  3839.     (if com (vip-execute-com 'vip-forward-sentence nil com))))
  3840.  
  3841. (defun vip-backward-sentence (arg)
  3842.   "Backward sentence."
  3843.   (interactive "P")
  3844.   (push-mark nil t) 
  3845.   (let ((val (vip-p-val arg))
  3846.     (com (vip-getcom arg)))
  3847.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3848.     (backward-sentence val)
  3849.     (if com (vip-execute-com 'vip-backward-sentence nil com))))
  3850.  
  3851. (defun vip-forward-paragraph (arg)
  3852.   "Forward paragraph."
  3853.   (interactive "P")
  3854.   (push-mark nil t) 
  3855.   (let ((val (vip-p-val arg))
  3856.     (com (vip-getCom arg)))
  3857.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3858.     (forward-paragraph val)
  3859.     (if com
  3860.     (progn
  3861.       (backward-char 1)
  3862.       (vip-execute-com 'vip-forward-paragraph nil com)))))
  3863.  
  3864. (defun vip-backward-paragraph (arg)
  3865.   "Backward paragraph."
  3866.   (interactive "P")
  3867.   (push-mark nil t) 
  3868.   (let ((val (vip-p-val arg))
  3869.     (com (vip-getCom arg)))
  3870.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3871.     (backward-paragraph val)
  3872.     (if com
  3873.     (progn
  3874.       (forward-char 1)
  3875.       (vip-execute-com 'vip-backward-paragraph nil com)
  3876.       (backward-char 1)))))
  3877.  
  3878. ;; should be mode-specific etc.
  3879.  
  3880. (defun vip-prev-heading (arg)
  3881.   (interactive "P")
  3882.   (let ((val (vip-p-val arg))
  3883.     (com (vip-getCom arg)))
  3884.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3885.     (re-search-backward vip-heading-start nil t val)
  3886.     (goto-char (match-beginning 0))
  3887.     (if com (vip-execute-com 'vip-prev-heading nil com))))
  3888.  
  3889. (defun vip-heading-end (arg)
  3890.   (interactive "P")
  3891.   (let ((val (vip-p-val arg))
  3892.     (com (vip-getCom arg)))
  3893.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3894.     (re-search-forward vip-heading-end nil t val)
  3895.     (goto-char (match-beginning 0))
  3896.     (if com (vip-execute-com 'vip-heading-end nil com))))
  3897.  
  3898. (defun vip-next-heading (arg)
  3899.   (interactive "P")
  3900.   (let ((val (vip-p-val arg))
  3901.     (com (vip-getCom arg)))
  3902.     (if com (vip-move-marker-locally 'vip-com-point (point)))
  3903.     (end-of-line)
  3904.     (re-search-forward vip-heading-start nil t val)
  3905.     (goto-char (match-beginning 0))
  3906.     (if com (vip-execute-com 'vip-next-heading nil com))))
  3907.  
  3908.  
  3909. ;; scrolling
  3910.  
  3911. (setq scroll-step 1)
  3912.  
  3913. (defun vip-scroll (arg)
  3914.   "Scroll to next screen."
  3915.   (interactive "p")
  3916.   (if (> arg 0)
  3917.       (while (> arg 0)
  3918.     (scroll-up)
  3919.     (setq arg (1- arg)))
  3920.     (while (> 0 arg)
  3921.       (scroll-down)
  3922.       (setq arg (1+ arg)))))
  3923.  
  3924. (defun vip-scroll-back (arg)
  3925.   "Scroll to previous screen."
  3926.   (interactive "p")
  3927.   (vip-scroll (- arg)))
  3928.  
  3929. (defun vip-scroll-down (arg)
  3930.   "Pull down half screen."
  3931.   (interactive "P")
  3932.   (condition-case nil
  3933.       (if (null arg)
  3934.       (scroll-down (/ (window-height) 2))
  3935.     (scroll-down arg))
  3936.     (error (beep 1)
  3937.        (message "Beginning of buffer")
  3938.        (goto-char (point-min)))))
  3939.  
  3940. (defun vip-scroll-down-one (arg)
  3941.   "Scroll up one line."
  3942.   (interactive "p")
  3943.   (scroll-down arg))
  3944.  
  3945. (defun vip-scroll-up (arg)
  3946.   "Pull up half screen."
  3947.   (interactive "P")
  3948.   (condition-case nil
  3949.       (if (null arg)
  3950.       (scroll-up (/ (window-height) 2))
  3951.     (scroll-up arg))
  3952.     (error (beep 1)
  3953.        (message "End of buffer")
  3954.        (goto-char (point-max)))))
  3955.  
  3956. (defun vip-scroll-up-one (arg)
  3957.   "Scroll down one line."
  3958.   (interactive "p")
  3959.   (scroll-up arg))
  3960.  
  3961.  
  3962. ;; searching
  3963.  
  3964. (defun vip-if-string (prompt)
  3965.   (let ((s (vip-read-string-with-history
  3966.         prompt
  3967.         nil ; no initial
  3968.         'vip-search-history
  3969.         (car vip-search-history))))
  3970.     (if (not (string= s ""))
  3971.     (setq vip-s-string s))))  
  3972.     
  3973.     
  3974. (defun vip-toggle-search-style (arg) 
  3975.   "Toggle the value of vip-case-fold-search/vip-re-search.
  3976. Without prefix argument, will ask which search style to toggle. With prefix
  3977. arg 1,toggles vip-case-fold-search; with arg 2 toggles vip-re-search.
  3978.  
  3979. Although this function is bound to \\[vip-toggle-search-style], the most
  3980. convenient way to use it is to bind `//' to the macro
  3981. `1 M-x vip-toggle-search-style' and `///' to
  3982. `2 M-x vip-toggle-search-style'. In this way, hitting `//' quickly will
  3983. toggle case-fold-search and hitting `/' three times witth toggle regexp
  3984. search. Macros are more convenient in this case because they don't affect
  3985. the Emacs binding of `/'."
  3986.   (interactive "P")
  3987.   (let (msg)
  3988.     (cond ((or (eq arg 1)
  3989.            (and (null arg)
  3990.             (y-or-n-p (format "Search style: '%s'. Want '%s'? "
  3991.                       (if vip-case-fold-search
  3992.                       "case-insensitive" "case-sensitive")
  3993.                       (if vip-case-fold-search
  3994.                       "case-sensitive"
  3995.                     "case-insensitive")))))
  3996.        (setq vip-case-fold-search (null vip-case-fold-search))
  3997.        (if vip-case-fold-search
  3998.            (setq msg "Search becomes case-insensitive")
  3999.          (setq msg "Search becomes case-sensitive")))
  4000.       ((or (eq arg 2)
  4001.            (and (null arg)
  4002.             (y-or-n-p (format "Search style: '%s'. Want '%s'? "
  4003.                       (if vip-re-search
  4004.                       "regexp-search" "vanilla-search")
  4005.                       (if vip-re-search
  4006.                       "vanilla-search"
  4007.                     "regexp-search")))))
  4008.        (setq vip-re-search (null vip-re-search))
  4009.        (if vip-re-search
  4010.            (setq msg "Search becomes regexp-style")
  4011.          (setq msg "Search becomes vanilla-style")))
  4012.       (t
  4013.        (setq msg "Search style remains unchanged")))
  4014.     (prin1 msg t)))
  4015.  
  4016.  
  4017. (defun vip-search-forward (arg)
  4018.   "Search a string forward. 
  4019. ARG is used to find the ARG's occurrence of the string.
  4020. Null string will repeat previous search."
  4021.   (interactive "P")
  4022.   (let ((val (vip-P-val arg))
  4023.     (com (vip-getcom arg))
  4024.     (old-str vip-s-string))
  4025.     (setq vip-s-forward t)
  4026.     (vip-if-string "/")
  4027.     ;; this is not used at present, but may be used later
  4028.     (if (or (not (equal old-str vip-s-string))
  4029.         (not (markerp vip-local-search-start-marker))
  4030.         (not (marker-buffer vip-local-search-start-marker)))
  4031.     (setq vip-local-search-start-marker (point-marker)))
  4032.     (vip-search vip-s-string t val)
  4033.     (if com
  4034.     (progn
  4035.       (vip-move-marker-locally 'vip-com-point (mark t))
  4036.       (vip-execute-com 'vip-search-next val com)))))
  4037.  
  4038. (defun vip-search-backward (arg)
  4039.   "Search a string backward. 
  4040. ARG is used to find the ARG's occurrence of the string.
  4041. Null string will repeat previous search."
  4042.   (interactive "P")
  4043.   (let ((val (vip-P-val arg))
  4044.     (com (vip-getcom arg))
  4045.     (old-str vip-s-string))
  4046.     (setq vip-s-forward nil)
  4047.     (vip-if-string "?")
  4048.     ;; this is not used at present, but may be used later
  4049.     (if (or (not (equal old-str vip-s-string))
  4050.         (not (markerp vip-local-search-start-marker))
  4051.         (not (marker-buffer vip-local-search-start-marker)))
  4052.     (setq vip-local-search-start-marker (point-marker)))
  4053.     (vip-search vip-s-string nil val)
  4054.     (if com
  4055.     (progn
  4056.       (vip-move-marker-locally 'vip-com-point (mark t))
  4057.       (vip-execute-com 'vip-search-next val com)))))
  4058.       
  4059.  
  4060. ;; Search for COUNT's occurrence of STRING.
  4061. ;; Search is forward if FORWARD is non-nil, otherwise backward.
  4062. ;; INIT-POINT is the position where search is to start.
  4063. ;; Arguments:
  4064. ;;   (STRING FORW COUNT &optional NO-OFFSET INIT-POINT LIMIT FAIL-IF-NOT-FOUND)
  4065. (defun vip-search (string forward arg
  4066.               &optional no-offset init-point fail-if-not-found)
  4067.   (if (not (equal string ""))
  4068.     (let ((val (vip-p-val arg))
  4069.       (com (vip-getcom arg))
  4070.       (offset (not no-offset))
  4071.       (case-fold-search vip-case-fold-search)
  4072.       (start-point (or init-point (point))))
  4073.       (vip-deactivate-mark)
  4074.       (if forward
  4075.       (condition-case nil
  4076.           (progn
  4077.             (if offset (vip-forward-char-carefully))
  4078.             (if vip-re-search
  4079.             (progn
  4080.               (re-search-forward string nil nil val)
  4081.               (re-search-backward string))
  4082.           (search-forward string nil nil val)
  4083.           (search-backward string))
  4084.         ;; don't wait and don't flash in macros
  4085.         (or executing-kbd-macro
  4086.             (vip-flash-search-pattern))
  4087.         (if (not (equal start-point (point)))
  4088.             (push-mark start-point t))) 
  4089.         (search-failed
  4090.          (if (and (not fail-if-not-found) vip-search-wrap-around-t)
  4091.              (progn
  4092.            (message "Search wrapped around end of buffer")
  4093.            (goto-char (point-min))
  4094.            (vip-search string forward (cons 1 com) t start-point 'fail)
  4095.            ;; don't wait in macros
  4096.            (or executing-kbd-macro (sit-for 2))
  4097.            ;; delete the wrap-around message
  4098.            (message "")
  4099.            )
  4100.            (goto-char start-point)
  4101.            (error "`%s': %s not found"
  4102.               string
  4103.               (if vip-re-search "Pattern" "String"))
  4104.            )))
  4105.     ;; backward
  4106.         (condition-case nil
  4107.         (progn
  4108.           (if vip-re-search
  4109.           (re-search-backward string nil nil val)
  4110.             (search-backward string nil nil val))
  4111.           ;; don't wait and don't flash in macros
  4112.           (or executing-kbd-macro
  4113.           (vip-flash-search-pattern))
  4114.           (if (not (equal start-point (point)))
  4115.           (push-mark start-point t))) 
  4116.       (search-failed
  4117.        (if (and (not fail-if-not-found) vip-search-wrap-around-t)
  4118.            (progn
  4119.          (message "Search wrapped around beginning of buffer")
  4120.              (goto-char (point-max))
  4121.              (vip-search string forward (cons 1 com) t start-point 'fail)
  4122.          ;; don't wait in macros
  4123.          (or executing-kbd-macro (sit-for 2))
  4124.          ;; delete the wrap-around message
  4125.          (message "")
  4126.          )
  4127.          (goto-char start-point)
  4128.          (error "`%s': %s not found"
  4129.             string
  4130.             (if vip-re-search "Pattern" "String"))
  4131.          )))))))
  4132.  
  4133. (defun vip-search-next (arg)
  4134.   "Repeat previous search."
  4135.   (interactive "P")
  4136.   (let ((val (vip-p-val arg))
  4137.     (com (vip-getcom arg)))
  4138.     (if (null vip-s-string) (error vip-NoPrevSearch))
  4139.     (vip-search vip-s-string vip-s-forward arg)
  4140.     (if com
  4141.     (progn
  4142.       (vip-move-marker-locally 'vip-com-point (mark t))
  4143.       (vip-execute-com 'vip-search-next val com)))))
  4144.  
  4145. (defun vip-search-Next (arg)
  4146.   "Repeat previous search in the reverse direction."
  4147.   (interactive "P")
  4148.   (let ((val (vip-p-val arg))
  4149.     (com (vip-getcom arg)))
  4150.     (if (null vip-s-string) (error vip-NoPrevSearch))
  4151.     (vip-search vip-s-string (not vip-s-forward) arg)
  4152.     (if com
  4153.     (progn
  4154.       (vip-move-marker-locally 'vip-com-point (mark t))
  4155.       (vip-execute-com 'vip-search-Next val com)))))
  4156.  
  4157.  
  4158. ;; Search contents of buffer defined by one of Viper's motion commands.
  4159. ;; Repeatable via `n' and `N'.
  4160. (defun vip-buffer-search-enable (&optional c)
  4161.   (cond (c (setq vip-buffer-search-char c))
  4162.     ((null vip-buffer-search-char)
  4163.      (setq vip-buffer-search-char ?g)))
  4164.   (define-key vip-vi-basic-map
  4165.     (char-to-string vip-buffer-search-char) 'vip-command-argument)
  4166.   (aset vip-exec-array vip-buffer-search-char 'vip-exec-buffer-search)
  4167.   (setq vip-prefix-commands (cons vip-buffer-search-char vip-prefix-commands)))
  4168.  
  4169. ;; This is a Viper wraper for isearch-forward.
  4170. (defun vip-isearch-forward (arg)
  4171.   "Do incremental search forward."
  4172.   (interactive "P")
  4173.   ;; emacs bug workaround
  4174.   (if (listp arg) (setq arg (car arg)))
  4175.   (vip-exec-form-in-emacs (list 'isearch-forward arg)))
  4176.  
  4177. ;; This is a Viper wraper for isearch-backward."
  4178. (defun vip-isearch-backward (arg)
  4179.   "Do incremental search backward."
  4180.   (interactive "P")
  4181.   ;; emacs bug workaround
  4182.   (if (listp arg) (setq arg (car arg)))
  4183.   (vip-exec-form-in-emacs (list 'isearch-backward arg)))
  4184.  
  4185.  
  4186. ;; visiting and killing files, buffers
  4187.  
  4188. (defun vip-switch-to-buffer ()
  4189.   "Switch to buffer in the current window."
  4190.   (interactive)
  4191.   (let (buffer)
  4192.     (setq buffer
  4193.       (read-buffer
  4194.        (format "Switch to buffer in this window \(%s\): "
  4195.            (buffer-name (other-buffer (current-buffer))))))
  4196.     (switch-to-buffer buffer)
  4197.     ))
  4198.  
  4199. (defun vip-switch-to-buffer-other-window ()
  4200.   "Switch to buffer in another window."
  4201.   (interactive)
  4202.   (let (buffer)
  4203.     (setq buffer
  4204.       (read-buffer
  4205.        (format "Switch to buffer in another window \(%s\): "
  4206.            (buffer-name (other-buffer (current-buffer))))))
  4207.     (switch-to-buffer-other-window buffer)
  4208.     ))
  4209.  
  4210. (defun vip-kill-buffer ()
  4211.   "Kill a buffer."
  4212.   (interactive)
  4213.   (let (buffer buffer-name)
  4214.     (setq buffer-name
  4215.       (read-buffer
  4216.        (format "Kill buffer \(%s\): "
  4217.            (buffer-name (current-buffer)))))
  4218.     (setq buffer
  4219.       (if (null buffer-name)
  4220.           (current-buffer)
  4221.         (get-buffer buffer-name)))
  4222.     (if (null buffer) (error "`%s': No such buffer" buffer-name))
  4223.     (if (or (not (buffer-modified-p buffer))
  4224.         (y-or-n-p 
  4225.          (format
  4226.           "Buffer `%s' is modified, are you sure you want to kill it? "
  4227.           buffer-name)))
  4228.     (kill-buffer buffer)
  4229.       (error "Buffer not killed"))))
  4230.  
  4231.  
  4232. (defvar vip-smart-suffix-list '("" "tex" "c" "cc" "el" "p")
  4233.   "*List of suffixes that Viper automatically tries to append to filenames ending with a `.'.
  4234. This is useful when you the current directory contains files with the same
  4235. prefix and many different suffixes. Usually, only one of the suffixes
  4236. represents an editable file. However, file completion will stop at the `.'
  4237. The smart suffix feature lets you hit RET in such a case, and Viper will
  4238. select the appropriate suffix.
  4239.  
  4240. Suffixes are tried in the order given and the first suffix for which a
  4241. corresponding file exists is selected. If no file exists for any of the
  4242. suffixes, the user is asked to confirm.
  4243.  
  4244. To turn this feature off, set this variable to nil.")
  4245.     
  4246. ;; Try to add suffix to files ending with a `.'
  4247. ;; Useful when the user hits RET on a non-completed file name.
  4248. (defun vip-file-add-suffix ()
  4249.   (let ((count 0)
  4250.     (len (length vip-smart-suffix-list))
  4251.     (file (buffer-string))
  4252.     found key cmd suff)
  4253.     (goto-char (point-max))
  4254.     (if (and vip-smart-suffix-list (string-match "\\.$" file))
  4255.     (progn
  4256.       (while (and (not found) (< count len))
  4257.         (setq suff (nth count vip-smart-suffix-list)
  4258.           count (1+ count))
  4259.         (if (file-exists-p (format "%s%s" file suff))
  4260.         (progn
  4261.           (setq found t)
  4262.           (insert suff))))
  4263.       
  4264.       (if found
  4265.           ()
  4266.         (vip-tmp-insert-at-eob " [Please complete file name]")
  4267.         (unwind-protect 
  4268.         (while (not (memq cmd '(exit-minibuffer vip-exit-minibuffer)))
  4269.           (setq cmd
  4270.             (key-binding (setq key (read-key-sequence nil))))
  4271.           (cond ((eq cmd 'self-insert-command)
  4272.              (if vip-xemacs-p
  4273.                  (insert (events-to-keys key))
  4274.                (insert key)))
  4275.             ((memq cmd '(exit-minibuffer vip-exit-minibuffer))
  4276.              nil)
  4277.             (t (command-execute cmd)))
  4278.           )))
  4279.           ))
  4280.     ))
  4281.  
  4282.  
  4283. ;; Advice for use in find-file and read-file-name commands.
  4284. (defadvice exit-minibuffer (before vip-exit-minibuffer-advice activate)
  4285.   "Run `vip-minibuffer-exit-hook' just before exiting the minibuffer."
  4286.   (run-hooks 'vip-minibuffer-exit-hook))
  4287.  
  4288. (defadvice find-file (before vip-add-suffix-advice activate)
  4289.   "Use `read-file-name' for reading arguments."
  4290.   (interactive (list (read-file-name "Find file: "
  4291.                      nil default-directory))))
  4292.     
  4293. (defadvice find-file-other-window (before vip-add-suffix-advice activate)
  4294.   "Use `read-file-name' for reading arguments."
  4295.   (interactive (list (read-file-name "Find file in other window: "
  4296.                      nil default-directory))))
  4297.     
  4298. (defadvice find-file-other-frame (before vip-add-suffix-advice activate)
  4299.   "Use `read-file-name' for reading arguments."
  4300.   (interactive (list (read-file-name "Find file in other frame: "
  4301.                      nil default-directory))))
  4302.  
  4303. (defadvice read-file-name (around vip-suffix-advice activate)
  4304.   "Tell `exit-minibuffer' to run `vip-file-add-suffix' as a hook."
  4305.   (let ((vip-minibuffer-exit-hook 'vip-file-add-suffix))
  4306.     ad-do-it))
  4307.  
  4308.      
  4309.  
  4310. ;; yank and pop
  4311.  
  4312. (defsubst vip-yank (text)
  4313.   "Yank TEXT silently. This works correctly with Emacs's yank-pop command."
  4314.     (insert text)
  4315.     (setq this-command 'yank))
  4316.  
  4317. (defun vip-put-back (arg)
  4318.   "Put back after point/below line."
  4319.   (interactive "P")
  4320.   (let ((val (vip-p-val arg))
  4321.     (text (if vip-use-register
  4322.           (cond ((vip-valid-register vip-use-register '(digit))
  4323.              (current-kill (- vip-use-register ?1) 'do-not-rotate))
  4324.             ((vip-valid-register vip-use-register)
  4325.              (get-register (downcase vip-use-register)))
  4326.             (t (error vip-InvalidRegister vip-use-register)))
  4327.         (current-kill 0))))
  4328.     (if (null text)
  4329.     (if vip-use-register
  4330.         (let ((reg vip-use-register))
  4331.           (setq vip-use-register nil)
  4332.           (error vip-EmptyRegister reg))
  4333.       (error "")))
  4334.     (setq vip-use-register nil)
  4335.     (if (vip-end-with-a-newline-p text)
  4336.     (progn
  4337.       (if (eobp)
  4338.           (insert "\n")
  4339.         (forward-line 1))
  4340.       (beginning-of-line))
  4341.       (if (not (eolp)) (vip-forward-char-carefully)))
  4342.     (set-marker (vip-mark-marker) (point) (current-buffer))
  4343.     (vip-set-destructive-command
  4344.      (list 'vip-put-back val nil vip-use-register nil nil))
  4345.     (vip-loop val (vip-yank text)))
  4346.   ;; Vi puts cursor on the last char when the yanked text doesn't contain a
  4347.   ;; newline; it leaves the cursor at the beginning when the text contains 
  4348.   ;; a newline
  4349.   (if (vip-same-line (point) (mark))
  4350.       (or (= (point) (mark)) (vip-backward-char-carefully))
  4351.     (exchange-point-and-mark)
  4352.     (if (bolp)
  4353.     (back-to-indentation)))
  4354.   (vip-deactivate-mark))
  4355.  
  4356. (defun vip-Put-back (arg)
  4357.   "Put back at point/above line."
  4358.   (interactive "P")
  4359.   (let ((val (vip-p-val arg))
  4360.     (text (if vip-use-register
  4361.           (cond ((vip-valid-register vip-use-register '(digit))
  4362.              (current-kill (- vip-use-register ?1) 'do-not-rotate))
  4363.             ((vip-valid-register vip-use-register)
  4364.              (get-register (downcase vip-use-register)))
  4365.             (t (error vip-InvalidRegister vip-use-register)))
  4366.         (current-kill 0))))
  4367.     (if (null text)
  4368.     (if vip-use-register
  4369.         (let ((reg vip-use-register))
  4370.           (setq vip-use-register nil)
  4371.           (error vip-EmptyRegister reg))
  4372.       (error "")))
  4373.     (setq vip-use-register nil)
  4374.     (if (vip-end-with-a-newline-p text) (beginning-of-line))
  4375.     (vip-set-destructive-command
  4376.      (list 'vip-Put-back val nil vip-use-register nil nil))
  4377.     (set-marker (vip-mark-marker) (point) (current-buffer))
  4378.     (vip-loop val (vip-yank text)))
  4379.   ;; Vi puts cursor on the last char when the yanked text doesn't contain a
  4380.   ;; newline; it leaves the cursor at the beginning when the text contains 
  4381.   ;; a newline
  4382.   (if (vip-same-line (point) (mark))
  4383.       (or (= (point) (mark)) (vip-backward-char-carefully))
  4384.     (exchange-point-and-mark)
  4385.     (if (bolp)
  4386.     (back-to-indentation)))
  4387.   (vip-deactivate-mark))
  4388.     
  4389.  
  4390. ;; Copy region to kill-ring.
  4391. ;; If BEG and END do not belong to the same buffer, copy empty region.
  4392. (defun vip-copy-region-as-kill (beg end)
  4393.   (condition-case nil
  4394.       (copy-region-as-kill beg end)
  4395.     (error (copy-region-as-kill beg beg))))
  4396.     
  4397.  
  4398. (defun vip-delete-char (arg)
  4399.   "Delete character."
  4400.   (interactive "P")
  4401.   (let ((val (vip-p-val arg)))
  4402.     (vip-set-destructive-command (list 'vip-delete-char val nil nil nil nil))
  4403.     (if (> val 1)
  4404.     (save-excursion
  4405.       (let ((here (point)))
  4406.         (end-of-line)
  4407.         (if (> val (- (point) here))
  4408.         (setq val (- (point) here))))))
  4409.     (if (and (eq val 0) (not vip-ex-style-motion)) (setq val 1))
  4410.     (if (and vip-ex-style-motion (eolp))
  4411.     (if (bolp) (error "") (setq val 0))) ; not bol---simply back 1 ch
  4412.     (if vip-use-register
  4413.     (progn
  4414.       (cond ((vip-valid-register vip-use-register '((Letter)))
  4415.          (vip-append-to-register
  4416.           (downcase vip-use-register) (point) (- (point) val)))
  4417.         ((vip-valid-register vip-use-register)
  4418.          (copy-to-register
  4419.           vip-use-register (point) (- (point) val) nil))
  4420.         (t (error vip-InvalidRegister vip-use-register)))
  4421.       (setq vip-use-register nil)))
  4422.     (if vip-ex-style-motion
  4423.     (progn
  4424.       (delete-char val t)
  4425.       (if (and (eolp) (not (bolp))) (backward-char 1)))
  4426.       (if (eolp)
  4427.           (delete-backward-char val t)
  4428.         (delete-char val t)))))
  4429.  
  4430. (defun vip-delete-backward-char (arg)
  4431.   "Delete previous character. On reaching beginning of line, stop and beep."
  4432.   (interactive "P")
  4433.   (let ((val (vip-p-val arg)))
  4434.     (vip-set-destructive-command
  4435.      (list 'vip-delete-backward-char val nil nil nil nil))
  4436.     (if (> val 1)
  4437.     (save-excursion
  4438.       (let ((here (point)))
  4439.         (beginning-of-line)
  4440.         (if (> val (- here (point)))
  4441.         (setq val (- here (point)))))))
  4442.     (if vip-use-register
  4443.     (progn
  4444.       (cond ((vip-valid-register vip-use-register '(Letter))
  4445.          (vip-append-to-register
  4446.           (downcase vip-use-register) (point) (+ (point) val)))
  4447.         ((vip-valid-register vip-use-register)
  4448.          (copy-to-register
  4449.           vip-use-register (point) (+ (point) val) nil))
  4450.         (t (error vip-InvalidRegister vip-use-register)))
  4451.       (setq vip-use-register nil)))
  4452.     (if (bolp) (ding)
  4453.       (delete-backward-char val t))))
  4454.       
  4455. (defun vip-del-backward-char-in-insert ()
  4456.   "Delete 1 char backwards while in insert mode."
  4457.   (interactive)      
  4458.   (if (and vip-ex-style-editing-in-insert (bolp))
  4459.       (beep 1)
  4460.     (delete-backward-char 1 t)))
  4461.       
  4462. (defun vip-del-backward-char-in-replace ()
  4463.   "Delete one character in replace mode.
  4464. If `vip-delete-backwards-in-replace' is t, then DEL key actually deletes
  4465. charecters. If it is nil, then the cursor just moves backwards, similarly
  4466. to Vi. The variable `vip-ex-style-editing-in-insert', if t, doesn't let the
  4467. cursor move past the beginning of line."
  4468.   (interactive)
  4469.   (cond (vip-delete-backwards-in-replace
  4470.      (cond ((not (bolp))
  4471.         (delete-backward-char 1 t))
  4472.            (vip-ex-style-editing-in-insert
  4473.         (beep 1))
  4474.            ((bobp)
  4475.         (beep 1))
  4476.            (t
  4477.         (delete-backward-char 1 t))))
  4478.     (vip-ex-style-editing-in-insert
  4479.      (if (bolp)
  4480.          (beep 1)
  4481.        (backward-char 1)))
  4482.     (t 
  4483.      (backward-char 1))))
  4484.  
  4485.  
  4486.  
  4487. ;; join lines.
  4488.  
  4489. (defun vip-join-lines (arg)
  4490.   "Join this line to next, if ARG is nil.  Otherwise, join ARG lines."
  4491.   (interactive "*P")
  4492.   (let ((val (vip-P-val arg)))
  4493.     (vip-set-destructive-command (list 'vip-join-lines val nil nil nil nil))
  4494.     (vip-loop (if (null val) 1 (1- val))
  4495.           (progn
  4496.         (end-of-line)
  4497.         (if (not (eobp))
  4498.             (progn
  4499.               (forward-line 1)
  4500.               (delete-region (point) (1- (point)))
  4501.               (fixup-whitespace)))))))
  4502.  
  4503.  
  4504. ;; Replace state
  4505.  
  4506. (defun vip-change (beg end)
  4507.   (if (markerp beg) (setq beg (marker-position beg)))
  4508.   (if (markerp end) (setq end (marker-position end)))
  4509.   ;; beg is sometimes (mark t), which may be nil
  4510.   (or beg (setq beg end))
  4511.   
  4512.   (vip-set-complex-command-for-undo)
  4513.   (if vip-use-register
  4514.       (progn
  4515.     (copy-to-register vip-use-register beg end nil)
  4516.     (setq vip-use-register nil)))
  4517.   (vip-set-replace-overlay beg end)
  4518.   (setq last-command nil) ; separate repl text from prev kills
  4519.   
  4520.   (if (= (vip-replace-start) (point-max))
  4521.       (error "End of buffer"))
  4522.       
  4523.   (setq vip-last-replace-region
  4524.     (buffer-substring (vip-replace-start)
  4525.               (vip-replace-end)))
  4526.   
  4527.   ;; protect against error while inserting "@" and other disasters
  4528.   ;; (e.g., read-only buff)
  4529.   (condition-case conds
  4530.       (if (vip-same-line (vip-replace-start)
  4531.              (vip-replace-end))
  4532.       (progn
  4533.         ;; tabs cause problems in replace, so untabify
  4534.         (goto-char (vip-replace-end))
  4535.         (insert-before-markers "@") ; put placeholder after the TAB
  4536.         (untabify (vip-replace-start) (point))
  4537.         ;; del @, don't put on kill ring 
  4538.         (delete-backward-char 1)
  4539.         
  4540.         (vip-set-replace-overlay-glyphs
  4541.          vip-replace-region-start-delimiter
  4542.          vip-replace-region-end-delimiter)
  4543.         ;; this move takes care of the last posn in the overlay, which
  4544.         ;; has to be shifted because of insert. We can't simply insert
  4545.         ;; "$" before-markers because then overlay-start will shift the
  4546.         ;; beginning of the overlay in case we are replacing a single
  4547.         ;; character. This fixes the bug with `s' and `cl' commands.
  4548.         (vip-move-replace-overlay (vip-replace-start) (point))
  4549.         (goto-char (vip-replace-start))
  4550.         (vip-change-state-to-replace t))
  4551.     (kill-region (vip-replace-start)
  4552.              (vip-replace-end))
  4553.     (vip-hide-replace-overlay)
  4554.     (vip-change-state-to-insert))
  4555.     (error ;; make sure that the overlay doesn't stay.
  4556.            ;; go back to the original point
  4557.      (goto-char (vip-replace-start))
  4558.      (vip-hide-replace-overlay)
  4559.      (vip-message-conditions conds))))
  4560.  
  4561.  
  4562. (defun vip-change-subr (beg end)
  4563.   ;; beg is sometimes (mark t), which may be nil
  4564.   (or beg (setq beg end))
  4565.   
  4566.   (if vip-use-register
  4567.       (progn
  4568.     (copy-to-register vip-use-register beg end nil)
  4569.     (setq vip-use-register nil)))
  4570.   (kill-region beg end)
  4571.   (setq this-command 'vip-change)
  4572.   (vip-yank-last-insertion))
  4573.  
  4574. (defun vip-toggle-case (arg)
  4575.   "Toggle character case."
  4576.   (interactive "P")
  4577.   (let ((val (vip-p-val arg)) (c))
  4578.     (vip-set-destructive-command (list 'vip-toggle-case val nil nil nil nil))
  4579.     (while (> val 0)
  4580.       (setq c (following-char))
  4581.       (delete-char 1 nil)
  4582.       (if (eq c (upcase c))
  4583.       (insert-char (downcase c) 1)
  4584.     (insert-char (upcase c) 1))
  4585.       (if (eolp) (backward-char 1))
  4586.       (setq val (1- val)))))
  4587.  
  4588.  
  4589. ;; query replace
  4590.  
  4591. (defun vip-query-replace ()
  4592.   "Query replace. 
  4593. If a null string is suplied as the string to be replaced,
  4594. the query replace mode will toggle between string replace
  4595. and regexp replace."
  4596.   (interactive)
  4597.   (let (str)
  4598.     (setq str (vip-read-string-with-history
  4599.            (if vip-re-query-replace "Query replace regexp: "
  4600.          "Query replace: ")
  4601.            nil  ; no initial
  4602.            'vip-replace1-history
  4603.            (car vip-replace1-history) ; default
  4604.            ))
  4605.     (if (string= str "")
  4606.     (progn
  4607.       (setq vip-re-query-replace (not vip-re-query-replace))
  4608.       (message "Query replace mode changed to %s"
  4609.            (if vip-re-query-replace "regexp replace"
  4610.              "string replace")))
  4611.       (if vip-re-query-replace
  4612.       (query-replace-regexp
  4613.        str
  4614.        (vip-read-string-with-history
  4615.         (format "Query replace regexp `%s' with: " str)
  4616.         nil  ; no initial
  4617.         'vip-replace1-history
  4618.         (car vip-replace1-history) ; default
  4619.         ))
  4620.     (query-replace
  4621.      str
  4622.      (vip-read-string-with-history
  4623.       (format "Query replace `%s' with: " str)
  4624.       nil  ; no initial
  4625.       'vip-replace1-history
  4626.       (car vip-replace1-history) ; default
  4627.       ))))))
  4628.  
  4629.  
  4630. ;; marking
  4631.  
  4632. (defun vip-mark-beginning-of-buffer ()
  4633.   "Mark beginning of buffer."
  4634.   (interactive)
  4635.   (push-mark (point))
  4636.   (goto-char (point-min))
  4637.   (exchange-point-and-mark)
  4638.   (message "Mark set at the beginning of buffer"))
  4639.  
  4640. (defun vip-mark-end-of-buffer ()
  4641.   "Mark end of buffer."
  4642.   (interactive)
  4643.   (push-mark (point))
  4644.   (goto-char (point-max))
  4645.   (exchange-point-and-mark)
  4646.   (message "Mark set at the end of buffer"))
  4647.  
  4648. (defun vip-mark-point ()
  4649.   "Set mark at point of buffer."
  4650.   (interactive)
  4651.   (let ((char (vip-read-char-exclusive)))
  4652.   (cond ((and (<= ?a char) (<= char ?z))
  4653.      (point-to-register (1+ (- char ?a))))
  4654.     ((= char ?<) (vip-mark-beginning-of-buffer))
  4655.     ((= char ?>) (vip-mark-end-of-buffer))
  4656.     ((= char ?.) (vip-set-mark-if-necessary))
  4657.     ((= char ?,) (vip-cycle-through-mark-ring))
  4658.     ((= char ?D) (mark-defun))
  4659.     (t (error ""))
  4660.     )))
  4661.     
  4662. ;; Algorithm: If first invocation of this command save mark on ring, goto
  4663. ;; mark, M0, and pop the most recent elt from the mark ring into mark,
  4664. ;; making it into the new mark, M1.
  4665. ;; Push this mark back and set mark to the original point position, p1.
  4666. ;; So, if you hit '' or `` then you can return to p1.
  4667. ;;
  4668. ;; If repeated command, pop top elt from the ring into mark and
  4669. ;; jump there. This forgets the position, p1, and puts M1 back into mark.
  4670. ;; Then we save the current pos, which is M0, jump to M1 and pop M2 from
  4671. ;; the ring into mark.  Push M2 back on the ring and set mark to M0.
  4672. ;; etc.
  4673. (defun vip-cycle-through-mark-ring ()
  4674.   "Visit previous locations on the mark ring.
  4675. One can use `` and '' to temporarily jump 1 step back."
  4676.   (let* ((sv-pt (point)))
  4677.        ;; if repeated `m,' command, pop the previously saved mark.
  4678.        ;; Prev saved mark is actually prev saved point. It is used if the
  4679.        ;; user types `` or '' and is discarded 
  4680.        ;; from the mark ring by the next `m,' command. 
  4681.        ;; In any case, go to the previous or previously saved mark.
  4682.        ;; Then push the current mark (popped off the ring) and set current
  4683.        ;; point to be the mark. Current pt as mark is discarded by the next
  4684.        ;; m, command.
  4685.        (if (eq last-command 'vip-cycle-through-mark-ring)
  4686.        ()
  4687.      ;; save current mark if the first iteration
  4688.      (setq mark-ring (delete (vip-mark-marker) mark-ring))
  4689.      (if (mark t)
  4690.          (push-mark (mark t) t)) )
  4691.        (pop-mark)
  4692.        (set-mark-command 1)
  4693.        ;; don't duplicate mark on the ring
  4694.        (setq mark-ring (delete (vip-mark-marker) mark-ring))
  4695.        (push-mark sv-pt t)
  4696.        (vip-deactivate-mark)
  4697.        (setq this-command 'vip-cycle-through-mark-ring)
  4698.        ))
  4699.        
  4700.  
  4701. (defun vip-goto-mark (arg)
  4702.   "Go to mark."
  4703.   (interactive "P")
  4704.   (let ((char (read-char))
  4705.     (com (vip-getcom arg)))
  4706.     (vip-goto-mark-subr char com nil)))
  4707.  
  4708. (defun vip-goto-mark-and-skip-white (arg)
  4709.   "Go to mark and skip to first non-white character on line."
  4710.   (interactive "P")
  4711.   (let ((char (read-char))
  4712.     (com (vip-getCom arg)))
  4713.     (vip-goto-mark-subr char com t)))
  4714.  
  4715. (defun vip-goto-mark-subr (char com skip-white)
  4716.   (if (eobp) 
  4717.       (if (bobp)
  4718.       (error "Empty buffer")
  4719.     (backward-char 1)))
  4720.   (cond ((vip-valid-register char '(letter))
  4721.      (let* ((buff (current-buffer))
  4722.             (reg (1+ (- char ?a)))
  4723.             (text-marker (get-register reg)))
  4724.        (if com (vip-move-marker-locally 'vip-com-point (point)))
  4725.        (if (not (vip-valid-marker text-marker))
  4726.            (error vip-EmptyTextmarker char))
  4727.        (if (and (vip-same-line (point) vip-last-jump)
  4728.             (= (point) vip-last-jump-ignore))
  4729.            (push-mark vip-last-jump t) 
  4730.          (push-mark nil t)) ; no msg
  4731.        (vip-register-to-point reg)
  4732.        (setq vip-last-jump (point-marker))
  4733.        (cond (skip-white 
  4734.           (back-to-indentation)
  4735.           (setq vip-last-jump-ignore (point))))
  4736.        (if com
  4737.            (if (equal buff (current-buffer))
  4738.            (vip-execute-com (if skip-white
  4739.                     'vip-goto-mark-and-skip-white
  4740.                       'vip-goto-mark)
  4741.                     nil com)
  4742.          (switch-to-buffer buff)
  4743.          (goto-char vip-com-point)
  4744.          (vip-change-state-to-vi)
  4745.          (error "")))))
  4746.     ((and (not skip-white) (= char ?`))
  4747.      (if com (vip-move-marker-locally 'vip-com-point (point)))
  4748.      (if (and (vip-same-line (point) vip-last-jump)
  4749.           (= (point) vip-last-jump-ignore))
  4750.          (goto-char vip-last-jump))
  4751.      (if (= (point) (mark t)) (pop-mark))
  4752.      (exchange-point-and-mark)
  4753.      (setq vip-last-jump (point-marker)
  4754.            vip-last-jump-ignore 0)
  4755.      (if com (vip-execute-com 'vip-goto-mark nil com)))
  4756.     ((and skip-white (= char ?'))
  4757.      (if com (vip-move-marker-locally 'vip-com-point (point)))
  4758.      (if (and (vip-same-line (point) vip-last-jump)
  4759.           (= (point) vip-last-jump-ignore))
  4760.          (goto-char vip-last-jump))
  4761.      (if (= (point) (mark t)) (pop-mark))
  4762.      (exchange-point-and-mark)
  4763.      (setq vip-last-jump (point))
  4764.      (back-to-indentation)
  4765.      (setq vip-last-jump-ignore (point))
  4766.      (if com (vip-execute-com 'vip-goto-mark-and-skip-white nil com)))
  4767.     (t (error vip-InvalidTextmarker char))))
  4768.     
  4769. (defun vip-insert-tab ()
  4770.   (interactive)
  4771.   (insert-tab))
  4772.  
  4773. (defun vip-exchange-point-and-mark ()
  4774.   (interactive)
  4775.   (exchange-point-and-mark)
  4776.   (back-to-indentation))
  4777.  
  4778. ;; Input Mode Indentation
  4779.  
  4780. ;; Returns t, if the string before point matches the regexp STR.
  4781. (defsubst vip-looking-back (str)
  4782.   (and (save-excursion (re-search-backward str nil t))
  4783.        (= (point) (match-end 0))))
  4784.  
  4785.  
  4786. (defun vip-forward-indent ()
  4787.   "Indent forward -- `C-t' in Vi."
  4788.   (interactive)
  4789.   (setq vip-cted t)
  4790.   (indent-to (+ (current-column) vip-shift-width)))
  4791.  
  4792. (defun vip-backward-indent ()
  4793.   "Backtab, C-d in VI"
  4794.   (interactive)
  4795.   (if vip-cted
  4796.       (let ((p (point)) (c (current-column)) bol (indent t))
  4797.     (if (vip-looking-back "[0^]")
  4798.         (progn
  4799.           (if (eq ?^ (preceding-char))
  4800.           (setq vip-preserve-indent t))
  4801.           (delete-backward-char 1)
  4802.           (setq p (point))
  4803.           (setq indent nil)))
  4804.     (save-excursion
  4805.       (beginning-of-line)
  4806.       (setq bol (point)))
  4807.     (if (re-search-backward "[^ \t]" bol 1) (forward-char))
  4808.     (delete-region (point) p)
  4809.     (if indent
  4810.         (indent-to (- c vip-shift-width)))
  4811.     (if (or (bolp) (vip-looking-back "[^ \t]"))
  4812.         (setq vip-cted nil)))))
  4813.  
  4814. (defun vip-autoindent ()
  4815.   "Auto Indentation, Vi-style."
  4816.   (interactive)
  4817.   (let ((col (current-indentation)))
  4818.     (if vip-preserve-indent
  4819.     (setq vip-preserve-indent nil)
  4820.       (setq vip-current-indent col))
  4821.     ;; don't leave whitespace lines around
  4822.     (if (memq last-command
  4823.           '(vip-autoindent
  4824.         vip-open-line vip-Open-line
  4825.         vip-replace-state-exit-cmd))
  4826.     (indent-to-left-margin))
  4827.     (newline 1)
  4828.     (if vip-auto-indent
  4829.     (progn
  4830.       (setq vip-cted t)
  4831.       (if vip-electric-mode
  4832.           (indent-according-to-mode)
  4833.         (indent-to vip-current-indent))
  4834.       ))
  4835.     ))
  4836.  
  4837.        
  4838. ;; Viewing registers
  4839.  
  4840. (defun vip-ket-function (arg)
  4841.   "Function called by \], the ket. View registers and call \]\]."
  4842.   (interactive "P")
  4843.   (let ((reg (read-char)))
  4844.     (cond ((vip-valid-register reg '(letter Letter))
  4845.        (view-register (downcase reg)))
  4846.       ((vip-valid-register reg '(digit))
  4847.        (let ((text (current-kill (- reg ?1) 'do-not-rotate)))
  4848.          (save-excursion 
  4849.            (set-buffer (get-buffer-create "*Output*"))
  4850.            (delete-region (point-min) (point-max))
  4851.            (insert (format "Register %c contains the string:\n" reg))
  4852.            (insert text)
  4853.            (goto-char (point-min)))
  4854.          (display-buffer "*Output*")))
  4855.       ((= ?\] reg)
  4856.        (vip-next-heading arg))
  4857.       (t (error
  4858.           vip-InvalidRegister reg)))))
  4859.  
  4860. (defun vip-brac-function (arg)
  4861.   "Function called by \[, the brac. View textmarkers and call \[\["
  4862.   (interactive "P")
  4863.   (let ((reg (read-char)))
  4864.     (cond ((= ?\[ reg)
  4865.        (vip-prev-heading arg))
  4866.       ((= ?\] reg)
  4867.        (vip-heading-end arg))
  4868.       ((vip-valid-register reg '(letter))
  4869.        (let* ((val (get-register (1+ (- reg ?a))))
  4870.           (buf (if (not val) 
  4871.                (error vip-EmptyTextmarker reg)
  4872.              (marker-buffer val)))
  4873.           (pos (marker-position val))
  4874.           line-no text (s pos) (e pos))
  4875.          (save-excursion 
  4876.            (set-buffer (get-buffer-create "*Output*"))
  4877.            (delete-region (point-min) (point-max))
  4878.            (if (and buf pos)
  4879.            (progn
  4880.              (save-excursion 
  4881.                (set-buffer buf)
  4882.                (setq line-no (1+ (count-lines (point-min) val)))
  4883.                (goto-char pos)
  4884.                (beginning-of-line)
  4885.                (if (re-search-backward "[^ \t]" nil t)
  4886.                (progn
  4887.                  (beginning-of-line)
  4888.                  (setq s (point))))
  4889.                (goto-char pos)
  4890.                (forward-line 1)
  4891.                (if (re-search-forward "[^ \t]" nil t)
  4892.                (progn
  4893.                  (end-of-line)
  4894.                  (setq e (point))))
  4895.                (setq text (buffer-substring s e))
  4896.                (setq text (format "%s<%c>%s" 
  4897.                       (substring text 0 (- pos s)) 
  4898.                       reg (substring text (- pos s)))))
  4899.              (insert
  4900.               (format
  4901.                "Textmarker `%c' is in buffer `%s' at line %d.\n"
  4902.                      reg (buffer-name buf) line-no))
  4903.              (insert (format "Here is some text around %c:\n\n %s" 
  4904.                      reg text)))
  4905.          (insert (format vip-EmptyTextmarker reg)))
  4906.            (goto-char (point-min)))
  4907.          (display-buffer "*Output*")))
  4908.       (t (error vip-InvalidTextmarker reg)))))
  4909.   
  4910.  
  4911.  
  4912. ;; commands in insertion mode
  4913.  
  4914. (defun vip-delete-backward-word (arg)
  4915.   "Delete previous word."
  4916.   (interactive "p")
  4917.   (save-excursion
  4918.     (push-mark nil t)
  4919.     (backward-word arg)
  4920.     (delete-region (point) (mark t))
  4921.     (pop-mark)))
  4922.  
  4923.  
  4924. (defun vip-set-expert-level (&optional dont-change-unless)
  4925.   "Sets the expert level for a Viper user.
  4926. Can be called interactively to change (temporarily or permanently) the
  4927. current expert level.
  4928.  
  4929. The optional argument DONT-CHANGE-UNLESS if not nil, says that
  4930. the level should not be changed, unless its current value is
  4931. meaningless (i.e., not one of 1,2,3,4,5).
  4932.  
  4933. User level determines the setting of Viper variables that are most
  4934. sensitive for VI-style look-and-feel."
  4935.   
  4936.   (interactive)
  4937.   
  4938.   (if (not (natnump vip-expert-level)) (setq vip-expert-level 0))
  4939.   
  4940.   (save-window-excursion
  4941.     (delete-other-windows)
  4942.     ;; if 0 < vip-expert-level < vip-max-expert-level
  4943.     ;;    & dont-change-unless = t -- use it; else ask
  4944.     (vip-ask-level dont-change-unless))
  4945.   
  4946.   (setq vip-always                      t
  4947.     vip-ex-style-motion             t
  4948.     vip-ex-style-editing-in-insert  t
  4949.     vip-want-ctl-h-help nil)
  4950.  
  4951.   (cond
  4952.     ;; a novice or a beginner
  4953.     ((eq vip-expert-level 1)
  4954.      (global-set-key vip-toggle-key   ;; in emacs-state
  4955.              (if (vip-window-display-p)
  4956.                  'vip-iconify
  4957.                'suspend-emacs))
  4958.      (setq vip-no-multiple-ESC         t
  4959.            vip-re-search                 t
  4960.            vip-vi-style-in-minibuffer    t
  4961.            vip-search-wrap-around-t         t
  4962.            vip-want-emacs-keys-in-vi     nil
  4963.            vip-want-emacs-keys-in-insert nil))
  4964.     
  4965.     ;; an intermediate to guru
  4966.     ((and (> vip-expert-level 1) (< vip-expert-level 5))
  4967.      (setq vip-no-multiple-ESC     (if (vip-window-display-p) t 'twice)
  4968.            vip-want-emacs-keys-in-vi     t
  4969.            vip-want-emacs-keys-in-insert (> vip-expert-level 2))
  4970.  
  4971.      (if (eq vip-expert-level 4) ; respect user's ex-style motions
  4972.                                   ; and vip-no-multiple-ESC
  4973.          (progn
  4974.            (setq-default vip-ex-style-editing-in-insert
  4975.                  (cdr (assoc 'vip-ex-style-editing-in-insert
  4976.                      vip-saved-user-settings))
  4977.                  vip-ex-style-motion
  4978.                  (cdr (assoc 'vip-ex-style-motion
  4979.                      vip-saved-user-settings)))
  4980.            (setq vip-ex-style-motion 
  4981.              (cdr (assoc 'vip-ex-style-motion vip-saved-user-settings))
  4982.              vip-ex-style-editing-in-insert
  4983.              (cdr (assoc 'vip-ex-style-editing-in-insert
  4984.                  vip-saved-user-settings))
  4985.              vip-re-search
  4986.              (cdr (assoc 'vip-re-search vip-saved-user-settings))
  4987.              vip-no-multiple-ESC 
  4988.              (cdr (assoc 'vip-no-multiple-ESC
  4989.                  vip-saved-user-settings))))))
  4990.            
  4991.     ;; A wizard
  4992.     ;; Ideally, if 5 is selected, a buffer should pop up to let the
  4993.     ;; user toggle variable values.
  4994.     (t (setq-default vip-ex-style-editing-in-insert
  4995.              (cdr (assoc 'vip-ex-style-editing-in-insert
  4996.                      vip-saved-user-settings))
  4997.              vip-ex-style-motion
  4998.              (cdr (assoc 'vip-ex-style-motion
  4999.                      vip-saved-user-settings)))
  5000.        (setq  vip-want-ctl-h-help 
  5001.           (cdr (assoc 'vip-want-ctl-h-help vip-saved-user-settings))
  5002.           vip-always
  5003.           (cdr (assoc 'vip-always vip-saved-user-settings))
  5004.           vip-no-multiple-ESC 
  5005.           (cdr (assoc 'vip-no-multiple-ESC vip-saved-user-settings))
  5006.           vip-ex-style-motion 
  5007.           (cdr (assoc 'vip-ex-style-motion vip-saved-user-settings))
  5008.           vip-ex-style-editing-in-insert
  5009.           (cdr (assoc 'vip-ex-style-editing-in-insert
  5010.                   vip-saved-user-settings))
  5011.           vip-re-search
  5012.           (cdr (assoc 'vip-re-search vip-saved-user-settings))
  5013.           vip-want-emacs-keys-in-vi 
  5014.           (cdr (assoc 'vip-want-emacs-keys-in-vi
  5015.                   vip-saved-user-settings))
  5016.           vip-want-emacs-keys-in-insert
  5017.           (cdr (assoc 'vip-want-emacs-keys-in-insert
  5018.                   vip-saved-user-settings)))))
  5019.   (vip-set-mode-vars-for vip-current-state)
  5020.   (if (or vip-always
  5021.       (and (> vip-expert-level 0) (> 5 vip-expert-level)))
  5022.       (vip-set-hooks)))
  5023.  
  5024. ;; Ask user expert level.
  5025. (defun vip-ask-level (dont-change-unless)
  5026.   (let ((ask-buffer " *vip-ask-level*")
  5027.     level-changed repeated)
  5028.     (save-window-excursion
  5029.       (switch-to-buffer ask-buffer)
  5030.           
  5031.       (or (eq this-command 'vip-set-expert-level)
  5032.       (and
  5033.        (<= vip-expert-level vip-max-expert-level)
  5034.        (>= vip-expert-level 1))
  5035.       (progn
  5036.         (insert "
  5037.           
  5038.           *** Important Notice for VIP users***
  5039.           
  5040.               This is VIPER
  5041.           
  5042. @joke
  5043. Viper Is a Package for Emacs Rebels,
  5044. a VI Plan for Emacs Rescue,
  5045. and a venomous VI PERil.
  5046. @end joke
  5047.  
  5048. Technically speaking, Viper is a new Vi emulator that replaces
  5049. the old VIP package.
  5050.  
  5051. Viper emulates Vi much better than VIP.  It also significantly
  5052. extends and improves upon Vi in many useful ways.
  5053.  
  5054. Although many VIP settings in your ~/.vip are compatible with Viper,
  5055. you may have to change some of them. Please refer to the documentation,
  5056. which can be obtained by executing
  5057.  
  5058. :help
  5059.  
  5060. when Viper is in Vi state.
  5061.  
  5062. If you will be so lucky as to find a bug, report it via the command
  5063.  
  5064. :submitReport
  5065.  
  5066. Type any key to continue... ")
  5067.         
  5068.         (read-char)
  5069.         (erase-buffer)))
  5070.           
  5071.       (while (or (> vip-expert-level vip-max-expert-level)
  5072.          (< vip-expert-level 1)
  5073.          (null dont-change-unless))
  5074.     (erase-buffer)
  5075.     (if repeated
  5076.         (progn
  5077.           (message "Invalid user level")
  5078.           (beep 1))
  5079.       (setq repeated t))
  5080.     (setq dont-change-unless t
  5081.           level-changed t)
  5082.     (insert "
  5083. Please specify your level of familiarity with the venomous VI PERil
  5084. (and the VI Plan for Emacs Rescue).
  5085. You can change it at any time by typing `M-x vip-set-expert-level RET'
  5086.     
  5087.  1 -- BEGINNER: Almost all Emacs features are suppressed.
  5088.           Feels almost like straight Vi. File name completion and
  5089.           command history in the minibuffer are thrown in as a bonus. 
  5090.           To use Emacs productively, you must reach level 3 or higher.
  5091.  2 -- MASTER: C-c now has its standard Emacs meaning in Vi command state,
  5092.       so most Emacs commands can be used when Viper is in Vi state.
  5093.       Good progress---you are well on the way to level 3!
  5094.  3 -- GRAND MASTER: Like 3, but most Emacs commands are available also
  5095.           in Viper's insert state.
  5096.  4 -- GURU: Like 3, but user settings are respected for vip-no-multiple-ESC,
  5097.       vip-re-search, vip-ex-style-motion, & vip-ex-style-editing-in-insert
  5098.       variables. Adjust these settings to your taste.
  5099.  5 -- WIZARD: Like 4, but user settings are also respected for vip-always,
  5100.       vip-want-ctl-h-help, vip-want-emacs-keys-in-vi, and 
  5101.       vip-want-emacs-keys-in-insert. Adjust these to your taste.
  5102.       
  5103. Please, specify your level now: ")
  5104.       
  5105.     (setq vip-expert-level (- (vip-read-char-exclusive) ?0))
  5106.     ) ; end while
  5107.       
  5108.       ;; tell the user if level was changed
  5109.       (and level-changed
  5110.        (progn
  5111.          (insert
  5112.           (format "\n\n\n\n\n\t\tYou have selected user level %d"
  5113.               vip-expert-level))
  5114.          (if (y-or-n-p "Do you wish to make this change permanent? ")
  5115.          ;; save the setting for vip-expert-level
  5116.          (vip-save-setting
  5117.           'vip-expert-level
  5118.           (format "Saving user level %d ..." vip-expert-level)
  5119.           vip-custom-file-name))
  5120.          ))
  5121.       (bury-buffer) ; remove ask-buffer from screen
  5122.       (message "")
  5123.       )))
  5124.  
  5125.  
  5126. (defun viper-version ()
  5127.   (interactive)
  5128.   (message "Viper version is %s" viper-version)) 
  5129.   
  5130. (defalias 'vip-version 'viper-version)
  5131.  
  5132. (defun vip-nil ()
  5133.   (interactive)
  5134.   (beep 1))
  5135.   
  5136.     
  5137. ;; if ENFORCE-BUFFER is not nil, error if CHAR is a marker in another buffer
  5138. (defun vip-register-to-point (char &optional enforce-buffer)
  5139.   "Like jump-to-register, but switches to another buffer in another window."
  5140.   (interactive "cViper register to point: ")
  5141.   (let ((val (get-register char)))
  5142.     (cond
  5143.      ((and (fboundp 'frame-configuration-p)
  5144.        (frame-configuration-p val))
  5145.       (set-frame-configuration val))
  5146.      ((window-configuration-p val)
  5147.       (set-window-configuration val))
  5148.      ((vip-valid-marker val)
  5149.       (if (and enforce-buffer
  5150.            (not (equal (current-buffer) (marker-buffer val))))
  5151.       (error (concat vip-EmptyTextmarker " in this buffer")
  5152.          (1- (+ char ?a))))
  5153.       (pop-to-buffer  (marker-buffer val))
  5154.       (goto-char val))
  5155.      ((and (consp val) (eq (car val) 'file))
  5156.       (find-file (cdr val)))
  5157.      (t
  5158.       (error vip-EmptyTextmarker (1- (+ char ?a)))))))
  5159.  
  5160.  
  5161. (defun vip-save-kill-buffer ()
  5162.   "Save then kill current buffer. "
  5163.   (interactive)
  5164.   (if (< vip-expert-level 2)
  5165.       (save-buffers-kill-emacs)
  5166.     (save-buffer)
  5167.     (kill-buffer (current-buffer))))
  5168.  
  5169.  
  5170.  
  5171. ;;; Bug Report
  5172.  
  5173. (defun vip-submit-report ()
  5174.   "Submit bug report on Viper."
  5175.   (interactive)
  5176.   (let ((reporter-prompt-for-summary-p t)
  5177.     (vip-device-type (vip-device-type))
  5178.     color-display-p frame-parameters
  5179.     minibuffer-emacs-face minibuffer-vi-face minibuffer-insert-face
  5180.     varlist salutation window-config)
  5181.     
  5182.     ;; If mode info is needed, add variable to `let' and then set it below,
  5183.     ;; like we did with color-display-p.
  5184.     (setq color-display-p (if (vip-window-display-p) 
  5185.                   (vip-color-display-p)
  5186.                 'non-x)
  5187.       minibuffer-vi-face (if (vip-has-face-support-p)
  5188.                  (vip-get-face vip-minibuffer-vi-face)
  5189.                    'non-x)
  5190.       minibuffer-insert-face (if (vip-has-face-support-p)
  5191.                      (vip-get-face vip-minibuffer-insert-face)
  5192.                    'non-x)
  5193.       minibuffer-emacs-face (if (vip-has-face-support-p)
  5194.                     (vip-get-face vip-minibuffer-emacs-face)
  5195.                   'non-x)
  5196.       frame-parameters (if (fboundp 'frame-parameters)
  5197.                    (frame-parameters (selected-frame))))
  5198.     
  5199.     (setq varlist (list 'vip-vi-minibuffer-minor-mode
  5200.                 'vip-insert-minibuffer-minor-mode
  5201.                 'vip-vi-intercept-minor-mode
  5202.                 'vip-vi-local-user-minor-mode     
  5203.                 'vip-vi-kbd-minor-mode            
  5204.                 'vip-vi-global-user-minor-mode
  5205.                 'vip-vi-state-modifier-minor-mode
  5206.                 'vip-vi-diehard-minor-mode   
  5207.                 'vip-vi-basic-minor-mode    
  5208.                 'vip-replace-minor-mode       
  5209.                 'vip-insert-intercept-minor-mode
  5210.                 'vip-insert-local-user-minor-mode 
  5211.                 'vip-insert-kbd-minor-mode         
  5212.                 'vip-insert-global-user-minor-mode
  5213.                 'vip-insert-state-modifier-minor-mode
  5214.                 'vip-insert-diehard-minor-mode     
  5215.                 'vip-insert-basic-minor-mode   
  5216.                 'vip-emacs-intercept-minor-mode 
  5217.                 'vip-emacs-local-user-minor-mode 
  5218.                 'vip-emacs-kbd-minor-mode 
  5219.                 'vip-emacs-global-user-minor-mode
  5220.                 'vip-emacs-state-modifier-minor-mode
  5221.                 'vip-automatic-iso-accents
  5222.                 'vip-want-emacs-keys-in-insert
  5223.                 'vip-want-emacs-keys-in-vi
  5224.                 'vip-keep-point-on-undo
  5225.                 'vip-no-multiple-ESC
  5226.                 'vip-ESC-key
  5227.                 'vip-want-ctl-h-help
  5228.                 'vip-ex-style-editing-in-insert
  5229.                 'vip-delete-backwards-in-replace
  5230.                 'vip-vi-style-in-minibuffer
  5231.                 'vip-vi-state-hook
  5232.                 'vip-insert-state-hook
  5233.                 'vip-replace-state-hook
  5234.                 'vip-emacs-state-hook
  5235.                 'ex-cycle-other-window
  5236.                 'ex-cycle-through-non-files
  5237.                 'vip-expert-level
  5238.                 'major-mode
  5239.                 'vip-device-type
  5240.             'color-display-p
  5241.             'frame-parameters
  5242.             'minibuffer-vi-face
  5243.             'minibuffer-insert-face
  5244.             'minibuffer-emacs-face
  5245.             ))
  5246.       (setq salutation "
  5247. Congratulations! You may have unearthed a bug in Viper!
  5248. Please mail a concise, accurate summary of the problem to the address above.
  5249.  
  5250. -------------------------------------------------------------------")
  5251.       (setq window-config (current-window-configuration))
  5252.       (with-output-to-temp-buffer " *vip-info*"
  5253.         (switch-to-buffer " *vip-info*")
  5254.         (delete-other-windows)
  5255.         (princ "
  5256. PLEASE FOLLOW THESE PROCEDURES
  5257. ------------------------------
  5258.  
  5259. Before reporting a bug, please verify that it is related to Viper, and is
  5260. not cause by other packages you are using.
  5261.  
  5262. Don't report compilation warnings, unless you are certain that there is a
  5263. problem. These warnings are normal and unavoidable.
  5264.  
  5265. Please note that users should not modify variables and keymaps other than
  5266. those advertised in the manual. Such `customization' is likely to crash
  5267. Viper, as it would any other improperly customized Emacs package.
  5268.  
  5269. If you are reporting an error message received while executing one of the
  5270. Viper commands, type:
  5271.  
  5272.     M-x set-variable <Return> debug-on-error <Return> t <Return>
  5273.     
  5274. Then reproduce the error. The above command will cause Emacs to produce a
  5275. back trace of the execution that leads to the error. Please include this
  5276. trace in your bug report.
  5277.  
  5278. If you believe that one of Viper's commands goes into an infinite loop
  5279. \(e.g., Emacs freezes\), type:
  5280.  
  5281.     M-x set-variable <Return> debug-on-quit <Return> t <Return>
  5282.     
  5283. Then reproduce the problem. Wait for a few seconds, then type C-g to abort
  5284. the current command. Include the resulting back trace in the bug report.
  5285.  
  5286. Mail anyway (y or n)? ")
  5287.         (if (y-or-n-p "Mail anyway? ")
  5288.         ()
  5289.           (set-window-configuration window-config)
  5290.           (error "Bug report aborted")))
  5291.  
  5292.       (require 'reporter)
  5293.       (set-window-configuration window-config)
  5294.     
  5295.       (reporter-submit-bug-report "kifer@cs.sunysb.edu"
  5296.                       (vip-version)
  5297.                       varlist
  5298.                       nil 'delete-other-windows
  5299.                       salutation)
  5300.       ))
  5301.             
  5302.  
  5303.     
  5304.         
  5305. ;; Smoothes out the difference between Emacs' unread-command-events
  5306. ;; and XEmacs unread-command-event. Arg is a character, an event, a list of
  5307. ;; events or a sequence of keys.
  5308. ;;
  5309. ;; Due to the way unread-command-events in Emacs (not XEmacs), a non-event
  5310. ;; symbol in unread-command-events list may cause Emacs to turn this symbol
  5311. ;; into an event. Below, we delete nil from event lists, since nil is the most
  5312. ;; common symbol that might appear in this wrong context.
  5313. (defun vip-set-unread-command-events (arg)
  5314.   (if vip-emacs-p
  5315.       (setq
  5316.        unread-command-events
  5317.        (let ((new-events
  5318.           (cond ((eventp arg) (list arg))
  5319.             ((listp arg) arg)
  5320.             ((sequencep arg)
  5321.              (listify-key-sequence arg))
  5322.             (t (error
  5323.             "vip-set-unread-command-events: Invalid argument, %S"
  5324.             arg)))))
  5325.      (if (not (eventp nil))
  5326.          (setq new-events (delq nil new-events)))
  5327.      (append new-events unread-command-events)))
  5328.     ;; XEmacs
  5329.     (setq
  5330.      unread-command-events
  5331.      (append
  5332.       (cond ((vip-characterp arg) (list (character-to-event arg)))
  5333.         ((eventp arg)  (list arg))
  5334.         ((stringp arg) (mapcar 'character-to-event arg))
  5335.         ((vectorp arg) (append arg nil)) ; turn into list
  5336.         ((listp arg) (vip-eventify-list-xemacs arg))
  5337.         (t (error
  5338.         "vip-set-unread-command-events: Invalid argument, %S" arg)))
  5339.       unread-command-events))))
  5340.  
  5341. ;; list is assumed to be a list of events of characters
  5342. (defun vip-eventify-list-xemacs (lis)
  5343.   (mapcar
  5344.    (function (lambda (elt)
  5345.            (cond ((vip-characterp elt) (character-to-event elt))
  5346.              ((eventp elt)  elt)
  5347.              (t (error
  5348.              "vip-eventify-list-xemacs: can't convert to event, %S"
  5349.              elt)))))
  5350.    lis))
  5351.   
  5352.   
  5353.  
  5354. ;;; Bring in the rest of the files
  5355. (require 'viper-mous)
  5356. (require 'viper-macs)
  5357. (require 'viper-ex)
  5358.  
  5359.  
  5360.  
  5361. ;; The following is provided for compatibility with older VIP's
  5362.  
  5363. (defalias 'vip-change-mode-to-vi 'vip-change-state-to-vi)
  5364. (defalias 'vip-change-mode-to-insert 'vip-change-state-to-insert)
  5365. (defalias 'vip-change-mode-to-emacs 'vip-change-state-to-emacs)
  5366.    
  5367.  
  5368.  
  5369. ;;; Load .vip and set up hooks
  5370.  
  5371. ;; This hook designed to enable Vi-style editing in comint-based modes."
  5372. (defun vip-comint-mode-hook ()
  5373.   (setq require-final-newline nil)
  5374.   (setq vip-ex-style-editing-in-insert nil
  5375.     vip-ex-style-motion nil)
  5376.   (vip-add-local-keys 'vi-state
  5377.               '(("\C-m" . comint-send-input) ; return
  5378.             ("\C-d" . comint-delchar-or-maybe-eof))) ; \C-d
  5379.   (vip-add-local-keys 'insert-state
  5380.               '(("\C-m" . comint-send-input) ; return
  5381.             ("\C-d" . comint-delchar-or-maybe-eof))) ; \C-d
  5382.   )
  5383.   
  5384.  
  5385. ;; This sets major mode hooks to make them come up in vi-state.
  5386. (defun vip-set-hooks ()
  5387.   
  5388.   ;; It is of course a misnomer to call viper-mode a `major mode'.
  5389.   ;; However, this has the effect that if the user didn't specify the
  5390.   ;; default mode, new buffers that fall back on the default will come up
  5391.   ;; in Fundamental Mode and Vi state.
  5392.   (setq default-major-mode 'viper-mode)
  5393.   
  5394.   ;; The following major modes should come up in vi-state
  5395.   (defadvice fundamental-mode (after vip-fundamental-mode-ad activate)
  5396.     "Run `vip-change-state-to-vi' on entry."
  5397.     (vip-change-state-to-vi))
  5398.  
  5399.   (defvar makefile-mode-hook)
  5400.   (add-hook 'makefile-mode-hook 'viper-mode)
  5401.  
  5402.   (defvar help-mode-hook)
  5403.   (add-hook 'help-mode-hook 'viper-mode)
  5404.  
  5405.   (defvar awk-mode-hook)
  5406.   (add-hook 'awk-mode-hook 'viper-mode)
  5407.   
  5408.   (defvar html-mode-hook)
  5409.   (add-hook 'html-mode-hook 'viper-mode)
  5410.   (defvar html-helper-mode-hook)
  5411.   (add-hook 'html-helper-mode-hook 'viper-mode)
  5412.   
  5413.   (defvar emacs-lisp-mode-hook)
  5414.   (add-hook 'emacs-lisp-mode-hook 'viper-mode)
  5415.  
  5416.   (defvar lisp-mode-hook)
  5417.   (add-hook 'lisp-mode-hook 'viper-mode)
  5418.   
  5419.   (defvar bibtex-mode-hook)
  5420.   (add-hook 'bibtex-mode-hook 'viper-mode)       
  5421.       
  5422.   (defvar cc-mode-hook)
  5423.   (add-hook 'cc-mode-hook 'viper-mode)
  5424.       
  5425.   (defvar c-mode-hook)
  5426.   (add-hook 'c-mode-hook 'viper-mode)
  5427.       
  5428.   (defvar c++-mode-hook)
  5429.   (add-hook 'c++-mode-hook 'viper-mode)
  5430.   
  5431.   (defvar lisp-interaction-mode-hook)
  5432.   (add-hook 'lisp-interaction-mode-hook 'viper-mode)
  5433.  
  5434.   (defvar fortran-mode-hook)
  5435.   (add-hook 'fortran-mode-hook 'vip-mode)
  5436.       
  5437.   (defvar text-mode-hook)
  5438.   (add-hook 'text-mode-hook 'viper-mode)
  5439.       
  5440.   (add-hook 'completion-list-mode-hook 'viper-mode)  
  5441.   (add-hook 'compilation-mode-hook     'viper-mode)  
  5442.  
  5443.   (add-hook 'perl-mode-hook     'viper-mode)  
  5444.   (add-hook 'tcl-mode-hook     'viper-mode)  
  5445.   
  5446.   (defvar emerge-startup-hook)
  5447.   (add-hook 'emerge-startup-hook 'vip-change-state-to-emacs)
  5448.   ;; Run vip-change-state-to-vi after quitting emerge.
  5449.   (vip-eval-after-load
  5450.    "emerge"
  5451.    '(defadvice emerge-quit (after vip-emerge-advice activate)
  5452.       "Run `vip-change-state-to-vi' after quitting emerge."
  5453.       (vip-change-state-to-vi)))
  5454.   ;; In case Emerge was loaded before Viper.
  5455.   (defadvice emerge-quit (after vip-emerge-advice activate)
  5456.     "Run `vip-change-state-to-vi' after quitting emerge."
  5457.     (vip-change-state-to-vi))
  5458.   
  5459.   (vip-eval-after-load
  5460.    "asm-mode"
  5461.    '(defadvice asm-mode (after vip-asm-mode-ad activate)
  5462.       "Run `vip-change-state-to-vi' on entry."
  5463.       (vip-change-state-to-vi)))
  5464.   
  5465.   ;; passwd.el sets up its own buffer, which turns up in Vi mode,
  5466.   ;; thus overriding the local map. We don't need Vi mode here.
  5467.   (vip-eval-after-load
  5468.    "passwd"
  5469.    '(defadvice read-passwd-1 (before vip-passwd-ad activate)
  5470.       "Switch to emacs state while reading password."
  5471.       (vip-change-state-to-emacs)))
  5472.  
  5473.   (vip-eval-after-load
  5474.    "prolog"
  5475.    '(defadvice prolog-mode (after vip-prolog-ad activate)
  5476.       "Switch to Vi state in Prolog mode."
  5477.       (vip-change-state-to-vi)))
  5478.   
  5479.   ;; Emacs shell, ange-ftp, and comint-based modes
  5480.   (defvar comint-mode-hook)
  5481.   (add-hook 'comint-mode-hook 'vip-change-state-to-insert)
  5482.   (add-hook 'comint-mode-hook 'vip-comint-mode-hook)
  5483.   
  5484.   ;; Shell scripts
  5485.   (defvar sh-mode-hook)
  5486.   (add-hook 'sh-mode-hook 'viper-mode)
  5487.   (defvar ksh-mode-hook)
  5488.   (add-hook 'ksh-mode-hook 'viper-mode)
  5489.   
  5490.   ;; Dired
  5491.   ;; This is only necessary when the user uses vip-modify-major-mode
  5492.   (add-hook 'dired-mode-hook 'vip-change-state-to-emacs)
  5493.  
  5494.   (if vip-emacs-p
  5495.       (progn
  5496.     (defvar view-mode-hook)
  5497.     (add-hook 'view-mode-hook 'vip-change-state-to-emacs))
  5498.     (defadvice view-minor-mode (after vip-view-ad activate)
  5499.       "Switch to Emacs state in View mode."
  5500.       (vip-change-state-to-emacs))
  5501.     (defvar view-hook)
  5502.     (add-hook 'view-hook 'vip-change-state-to-emacs))
  5503.   
  5504.   ;; For VM users.
  5505.   ;; Put summary and other VM buffers in Emacs state.
  5506.   (defvar vm-mode-hooks)
  5507.   (defvar vm-summary-mode-hooks)
  5508.   (add-hook 'vm-mode-hooks   'vip-change-state-to-emacs)
  5509.   (add-hook 'vm-summary-mode-hooks   'vip-change-state-to-emacs)
  5510.   
  5511.   ;; For RMAIL users.
  5512.   ;; Put buf in Emacs state after edit.
  5513.   (vip-eval-after-load
  5514.    "rmailedit"
  5515.    '(defadvice rmail-cease-edit (after vip-rmail-advice activate)
  5516.       "Switch to emacs state when done editing message."
  5517.       (vip-change-state-to-emacs)))
  5518.   ;; In case RMAIL was loaded before Viper.
  5519.   (defadvice rmail-cease-edit (after vip-rmail-advice activate)
  5520.     "Switch to emacs state when done editing message."
  5521.     (vip-change-state-to-emacs))
  5522.   ) ; vip-set-hooks
  5523.       
  5524. ;; Set some useful macros
  5525. ;; These must be before we load .vip, so the user can unrecord them.
  5526.  
  5527. ;; repeat the 2nd previous command without rotating the command history
  5528. (vip-record-kbd-macro
  5529.  (vector vip-repeat-from-history-key '\1) 'vi-state
  5530.  [(meta x) v i p - r e p e a t - f r o m - h i s t o r y return] 't)
  5531. ;; repeat the 3d previous command without rotating the command history
  5532. (vip-record-kbd-macro
  5533.  (vector vip-repeat-from-history-key '\2) 'vi-state
  5534.  [(meta x) v i p - r e p e a t - f r o m - h i s t o r y return] 't)
  5535.  
  5536. ;; toggle case sensitivity in search
  5537. (vip-record-kbd-macro
  5538.  "//" 'vi-state
  5539.  [1 (meta x) v i p - t o g g l e - s e a r c h - s t y l e return] 't)
  5540. ;; toggle regexp/vanila search
  5541. (vip-record-kbd-macro
  5542.  "///" 'vi-state
  5543.  [2 (meta x) v i p - t o g g l e - s e a r c h - s t y l e return] 't)
  5544.  
  5545.  
  5546. ;; ~/.vip is loaded if it exists
  5547. (if (and (file-exists-p vip-custom-file-name)
  5548.      (not noninteractive))
  5549.     (load vip-custom-file-name))
  5550.  
  5551. ;; VIP compatibility: merge whatever the user has in vip-mode-map into
  5552. ;; Viper's basic map.
  5553. (vip-add-keymap vip-mode-map vip-vi-global-user-map)
  5554.  
  5555.  
  5556. ;; Applying Viper customization -- runs after (load .vip)
  5557.  
  5558. ;; Save user settings or Viper defaults for vars controled by vip-expert-level
  5559. (setq vip-saved-user-settings 
  5560.       (list (cons 'vip-want-ctl-h-help vip-want-ctl-h-help)
  5561.         (cons 'vip-always vip-always)
  5562.         (cons 'vip-no-multiple-ESC vip-no-multiple-ESC)
  5563.         (cons 'vip-ex-style-motion vip-ex-style-motion)
  5564.         (cons 'vip-ex-style-editing-in-insert
  5565.                                     vip-ex-style-editing-in-insert) 
  5566.         (cons 'vip-want-emacs-keys-in-vi vip-want-emacs-keys-in-vi)
  5567.         (cons 'vip-want-emacs-keys-in-insert vip-want-emacs-keys-in-insert)
  5568.         (cons 'vip-re-search vip-re-search)))
  5569.           
  5570.  
  5571. (vip-set-minibuffer-style)
  5572. (vip-set-minibuffer-faces)
  5573. (vip-set-search-face)
  5574. (if vip-buffer-search-char
  5575.     (vip-buffer-search-enable))
  5576. (vip-update-alphanumeric-class)
  5577.    
  5578. ;;; Familiarize Viper with some minor modes that have their own keymaps
  5579. (vip-harness-minor-mode "compile")
  5580. (vip-harness-minor-mode "outline")
  5581. (vip-harness-minor-mode "allout")
  5582. (vip-harness-minor-mode "xref")
  5583. (vip-harness-minor-mode "lmenu")
  5584. (vip-harness-minor-mode "vc")
  5585. (vip-harness-minor-mode "ltx-math") ; LaTeX-math-mode in AUC-TeX
  5586. (vip-harness-minor-mode "latex")    ; which is in one of these two files
  5587. (vip-harness-minor-mode "cyrillic")
  5588. (vip-harness-minor-mode "russian")
  5589. (vip-harness-minor-mode "view-less")
  5590. (vip-harness-minor-mode "view")
  5591.  
  5592.  
  5593. ;; Intercept maps could go in viper-keym.el
  5594. ;; We keep them here in case someone redefines them in ~/.vip
  5595.  
  5596. (define-key vip-vi-intercept-map vip-ESC-key 'vip-intercept-ESC-key)
  5597. (define-key vip-insert-intercept-map vip-ESC-key 'vip-intercept-ESC-key)
  5598.  
  5599. ;; This is taken care of by vip-insert-global-user-map.
  5600. ;;(define-key vip-replace-map vip-ESC-key 'vip-intercept-ESC-key)
  5601.  
  5602. (define-key vip-insert-intercept-map vip-toggle-key 'vip-alternate-ESC)
  5603. ;; The default vip-toggle-key is \C-z; for the novice, it suspends or
  5604. ;; iconifies Emacs
  5605. (define-key vip-vi-intercept-map vip-toggle-key
  5606.   '(lambda () (interactive)
  5607.      (if (and (< vip-expert-level 2) (equal vip-toggle-key "\C-z"))
  5608.      (if (vip-window-display-p) (vip-iconify) (suspend-emacs))
  5609.        (vip-change-state-to-emacs))))
  5610.  
  5611. (define-key vip-emacs-intercept-map vip-toggle-key 'vip-change-state-to-vi)
  5612.  
  5613.  
  5614. (if (or vip-always 
  5615.     (and (< vip-expert-level 5) (> vip-expert-level 0)))
  5616.     (vip-set-hooks))
  5617.     
  5618. ;; Let all minor modes take effect after loading
  5619. ;; this may not be enough, so we also set default minor-mode-alist.
  5620. ;; Without setting the default, new buffers that come up in emacs mode have
  5621. ;; minor-mode-map-alist = nil, unless we call vip-change-state-*
  5622. (if (eq vip-current-state 'emacs-state)
  5623.     (progn
  5624.       (vip-change-state-to-emacs)
  5625.       (setq-default minor-mode-map-alist minor-mode-map-alist)
  5626.       ))
  5627.     
  5628.  
  5629. (run-hooks 'vip-load-hook) ; the last chance to change something
  5630.  
  5631. (provide 'viper)
  5632. (provide 'vip19)
  5633. (provide 'vip)
  5634.  
  5635. ;;;  viper.el ends here
  5636.